Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to change the underlying default package directory of python's subprocess module?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading