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
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!
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