简体   繁体   中英

Python: Trouble with cross platform running of subprocesses

I have the following helper method which executes commands perfectly on OSX and only with some commands on Windows:

def exec_cmd(cmd):
    """Run a command and return the status, standard output and error."""
    proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    # I like to get True or False rather than 0 (True) or 1 (False)
    # which is just backwards as usually 0 is False and 1 is True
    status = not bool(proc.returncode)
    return (status, stdout, stderr)

For example, the following sample commands all work perfectly on Mac using my exec_cmd helper:

  • osascript -e 'tell application "Microsoft PowerPoint" to activate
  • osascript -e 'tell application "Microsoft PowerPoint" to quit

For example, the following sample commands all work perfectly on Windows using my exec_cmd helper:

  • "C:\\Program Files\\Microsoft Office\\Office15\\Powerpnt.exe" /S "C:\\Users\\MyUser\\example.pptx"
  • Taskkill /IM POWERPNT.EXE /F

However, the following does not work on Windows:

  • START "" "C:\\Program Files\\Microsoft Office\\Office15\\Powerpnt.exe"

It errors out with:

WindowsError: [Error 2] The system cannot find the file specified

Even this doesn't work:

p = Popen(["START", "", "C:\Program Files\Microsoft Office\Office15\Powerpnt.exe"], stdout=PIPE, stderr=PIPE)

However running that same command on the command line works fine, or even stranger just doing this works:

os.system('START "" "C:\Program Files\Microsoft Office\Office15\Powerpnt.exe"')

Why does os.system work, but not the Popen version? These are just simple open and close app examples, but I'd like to do more as I need to get the stdout output for some commands I plan on running.

Any help on sorting this out is appreciated. I can't seem to understand the underlying mechanic of os.system vs. subprocess.Popen .

You are seeing this issue because START isn't a program, its a shell command. According to the documentation, os.system() "Executes the command (a string) in a subshell", where as popen doesn't. os.system() effectively spawns a new cmd.exe instance, and passes the command to that, where as popen just spawns a new process.

You are getting the The system cannot find the file specified error because there isn't a program called START

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