简体   繁体   中英

Python 3: subprocess, changing directory

I have a main project in C:/myproject/harry.py

harry.py is launching threads.

harry.py is saving and loading text documents every few seconds using an already established path self.relativePath = os.path.dirname(sys.argv[0])

Inside each thread, a subprocess is being called to activate a command line .exe file found in C:/myproject/betty/here.exe

I have tried all sorts of things to achieve this such as:

my_env = os.environ
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
doit = subprocess.Popen('cd betty/', 'here.exe -command', env=my_env)
doit.wait()

or

my_env = os.environ
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
doit = subprocess.Popen('here.exe -command', cwd='C:/myproject/betty/')
doit.wait()

Response:

FileNotFoundError: [WinError 2] The system cannot find the file specified

Is it possible to run the subprocess inside the subfolder with the custom path ... that will not interfere with the already established path self.relativePath

Thanks,

You were fairly close:

> doit = subprocess.Popen('here.exe -command', cwd='C:/myproject/betty/')

This would actually work if your command were called here.exe -command but of course, no such file exists. You want ['here.exe', '-command'] (or somewhat more unsafely and less efficiently add shell=True ; but really, don't).

It seems you forgot to pass in env=my_env in this attempt, too; though does here.exe really require you to modify the PATH ? And if it does, repeatedly creating a new copy for each new subprocess seems slightly wasteful.

You'll also want to switch to subprocess.run() or one of the legacy wrappers; you should really only use the low-level Popen() function directly from library functions.

On the other hand, does here.exe really need to run in a particular directory, and does that directory exist on your PATH ? Windows is slightly weird and Windows programmers are often unaware of basic command-line usability design principles; but if here.exe is at all correctly written, perhaps you are actually looking for

s = subprocess.run(['c:/myproject/betty/here.exe', '-command'], env=my_env)

I have discovered the answer with some help from various stackoverflow posts on the topic as well as stumbling through possible solutions. It was not easy!

self.relativePath = os.path.dirname(sys.argv[0])

self.relativePath1 = self.relativePath + '\\your_subdirectoryHERE\\'

Be sure to include double slashes, to match os.path.dirname(sys.argv[0])

self.process = subprocess.Popen(self.relativePath1 + 'flare.exe -command', cwd=self.relativePath1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM