Search code examples
pythonwindowssubprocesschocolatey

Why does subprocess.run create return code 1 even if the command was successful?


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 change its result. If I test a windows command like dir everything works as expected. Where is my mistake here?

Edited:

As some comments indicated it was not clear what I meant by options, actually I tried similar things as it was suggested already before. However, I was mislead by two things

  1. The idea that a call which I consider to be sucessful would alwas return 0 as code. A good explanation was given by Shine J.
  2. And it turned out that I tried to provide options inline. Instead I had to provide it as a second argument. From the documentation of Popen (which is called underneath) this became clear to me. Chocolatey also returns 0 as return code if called like this:
import subprocess
result = subprocess.run(['choco','-v'], capture_output=True)

print(result.returncode)

However, I believe that Shine J is right in saying that it is better to check if the file is present. Therefore, I will accept this as the correct answer. Thanks!


Solution

  • 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