pythonwindowspython-2.7os.system

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


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


Solution

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