2

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...

2
  • Is this of any help: stackoverflow.com/questions/1912818/…? Commented Dec 26, 2014 at 22:40
  • 1
    What about: os.system('""C:\\fe re\\python.exe" program "c:\\test now\\test.txt" http://site.to.explore"')? Commented Dec 26, 2014 at 22:44

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.