Home > Net >  Why does subprocess.run create return code 1 even if the command was successful? [closed]
Why does subprocess.run create return code 1 even if the command was successful? [closed]

Time:09-26

From within python, I am trying to check if chocolatey is installed on a windows machine. I used subprocess.run to implement that, however, the return code is 1 even if chocolatey is installed.

Here is my code:

import subprocess

result = subprocess.run(['choco'], capture_output=True, text=True)
print(result.returncode)

Adding options won't help. If I test a windows command like dir everything works as expected. Where is my mistake here?

CodePudding user response:

It totally depends on the value returned by your program with different arguments.

For example, when I run the following on my computer (git is installed):

result = subprocess.run(['git'], capture_output=True)

result.returncode is 1

If I run git with parameter --version like this:

result = subprocess.run(['git','--version'], capture_output=True)

result.returncode is 0

To really check if a program exists or not (on Windows) you could do something like:

try:
    result = subprocess.run(['choco'], capture_output=True)
    print(result)
except FileNotFoundError:
    print("Program not installed")

Check out this official documentation on Subprocess

CodePudding user response:

You ran choco without any arguments, meaning it didn't get a command to perform. It's up to choco whether that's regarded as an error; I suspect it is, much like if you passed it an unknown command. You may want to pass it a command that should succeed, such as choco help.

  • Related