How do I execute a program from python? os.system fails

Question:

I want to run a command with os.system but i get an error

c:/fe ' is not recognized as an internal or external command, operable program or batch file

The code I use is

import os
os.system('"C:\fe re\python.exe" program "c:\test now\test.txt" http://site.to.explore')

It will work if I only run:

import os
os.system('"C:\fe re\python.exe" program -h')

Or if I have no space in the python path like this

import os
os.system('C:\fere\python.exe program "c:\test now\test.txt" http://site.to.explore')

But if I have two pairs of double-quotes in the command both in python path and in txt path I get an error…

Asked By: user4224449

||

Answers:

os.system has some serious drawbacks, especially with space in filenames and w.r.t. security. I suggest you look into the subprocess module and particularly subprocess.check_call, which is much more powerful. You could then do e.g.

import subprocess
subprocess.check_call(["c:\fe re\python.exe", "program", etcetc...])

Of course, make sure to take great care not to have user-determined variables in these calls unless the user is already running the script herself from the command line with the same privileges.

Answered By: smocking

I don’t agree with the subprocess module being the accepted answer.

I can make the same call to the system in ANY other language and not have one single issue. This is broken in python.

Here is my simple solution though to getting around this:

os.chdir("C:\Program Files\7-Zip")
os.system("7z.exe e "{}" -o"{}"n".format(os.path.join(directory, file), self.out))

You simply change to the directory of your executable, then run the os.system command as normal.

Answered By: Seth