Home > Back-end >  Why does the "which" system command give a 256 code with os.system in python?
Why does the "which" system command give a 256 code with os.system in python?

Time:10-13

I am on mac OSX.

I have a program where I am trying to call downloaded libraries from the terminal. This is not possible if I don't know where the libraries are. I will use pip as a common library example

>>> os.system("pip -h")
32512
>>> os.system("which pip")
256

I have read this response to the 256 error, however, I still don't understand why it appears here. It says it is "frequently used to indicate an argument parsing failure" however the exact command works because this does not seem to be an argument parsing error to me.

I would like to be able to do something to the effect of:

os.system(os.system("which pip")  " -h")

If there is another way of doing this, I would love to hear it

CodePudding user response:

Don't use os.system like that (and don't use which, either). Try this to find a program:

import os

for bin_dir in os.environ.get("PATH").split(":"):
  if 'my_program' in os.listdir(bin_dir):
    executable_path = os.path.join(bin_dir, 'my_program')
    break

Note that this does assume that PATH was properly set by whatever process started the script. If you are running it from a shell, that shouldn't be an issue.

In general, using os.system to call common *NIX utilities and trying to parse the results is unidiomatic-- it's writing python as if it was a shell script.

Then, instead of using system to run pip, use the solution describe in this answer.

  • Related