On Linux systems, subprocess.run(["some_command"]) appears to scrape /usr/bin for some_command by default and thus, subprocess accepts every command that also has a respective binary in this directory.
I have a use case now, where I have binaries in multiple directories and I want to execute some of them with the subprocess module. Obviously, I can do something like:
subprocess.run(["/absolute/path/to/first_binary"])
subprocess.run(["/another/absolute/path/to/another/second_binary"])
But I was wondering if there exists anything like:
subprocess.set_bin_dirs(["/usr/bin/", "/absolute/path/to/", "/another/absolute/path/to/another/"])
subprocess.run(["first_binary"])
subprocess.run(["second_binary"])
>Solution :
This has nothing to do with Python and the subprocess module. This is a core idea about how Unix-like(and other) operating systems work, when you do some_command, that command is looked up on your PATH. So you must add that directories of these binaries to the PATH, otherwise, you need to use the full path when you try to execute a command, e.g. /usr/bin/some_command
To do this in Python with the subprocess module, you could do something like:
import os
env_copy = os.environ.copy()
current_path = current_env['PATH']
env_copy["PATH"] = os.pathsep.join([
"/usr/bin/",
"/absolute/path/to/",
"/another/absolute/path/to/another/",
current_path
])
subprocess.run(["some_command"], env=env_copy)
Note, paths are looked up in order, so the order in which you append it matters if there are possible name-collisions. Note, you don’t actually have to add the current PATH, but you might. All of this is up to you.