Search code examples
pythonpython-3.xsubprocesspathlib

How to use pathlib along with subprocess


I would like to use relative paths along with subprocess module in order to be able to run different executables.

For getting relative paths and, after reading different threads, I think pathlib module is the best option to do that.

Let assume I have the python script in a particular folder in Windows. Inside it (the previous folder), I have other folders with the executables I want to run. Here it is when subprocess module comes in. However, I do not know how to include the relative paths created with pathlib module into subprocess args field.

From subprocess API I can read that 'args should be a sequence of program arguments or else a single string'.

import pathlib
import subprocess

in_file_1 = pathlib.Path.cwd() / "folder2" / "folder3" / "whatever.exe"

p = subprocess.Popen(str(in_file_1), shell = True)

I would expect to see the whatever.exe process running on the administrator tasks but the process is not started. How can I achieve that? Is there something I am ingoring? Should I just give the relative path from where the python script is saved?


Solution

  • You are confusing the current working directory, which is what pathlib.Path.cwd() returns, with the script's location.

    If you want the script's dir, you can use __file__, for instance like this:

    import pathlib
    
    cwd = pathlib.Path.cwd()
    script_file = pathlib.Path(__file__)
    script_location = script_file.parent
    
    print("The current dir is", pathlib.Path.cwd())
    print("The current script is", script_file)
    print("The current script's dir is", script_file.parent)
    

    which will return:

    The current dir is /home/nicoco
    The current script is /tmp/so.py
    The current script's dir is /tmp