0

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

Jangwa
  • 5
  • 2
  • 256 means that `which` exited with status code 1, which means that the `pip` command could not be found. 32512 means that `pip -h` exited with status code 127, which is what the shell exits with when the command can't be found. TL;DR you don't have `pip` in your PATH. – Aplet123 Oct 13 '21 at 01:12
  • Use [os.waitstatus_to_exitcode](https://docs.python.org/3/library/os.html#os.waitstatus_to_exitcode) to get the exitcode from the returned wait status: `os.waitstatus_to_exitcode(256) == 1` – Iain Shelvington Oct 13 '21 at 01:16

1 Answers1

0

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.

Z4-tier
  • 7,287
  • 3
  • 26
  • 42