How to launch a program with many arguments in Python/Linux
The following code works fine in Windows:
subprocess.Popen([PATH_TO_G++]/g++ file.cpp -o file.exe)
However in Linux I get the following error:
OSError: [Errno 2] No such file or directory
After read开发者_如何学运维ing the documentation and several SO threads, I found out that subprocess.Popen works differently in Windows and nix systems. In windows it takes the string as the parameter and launches it just like you'd launch it in terminal.
In linux however it requires a list of strings if you have parameters. The first value is the program itself, then go the attributes. You can make it behave like Windows by passing the Shell=True argument, but that's not a good solution for me.
I tried the shlex.split function, but it still doesn't work.
Based on your example you'll need to make sure the command is properly quoted:
subprocess.Popen([PATH_TO_G++ + "/g++", "file.cpp", "-o", "file.exe"])
There is no way PATH_TO_G++ is a valid variable name, so I'm just going to assume that you provided that as an example.
Now, more importantly, what are you trying to do with the subprocess? Just launch it and have it be the primary operation? Launch it and capture the output? Launch it in the background?
The documentation for the subprocess module is pretty clear and provides a lot of examples on how you might use it.
精彩评论