[Tutor] Q regarding external program calling

eryk sun eryksun at gmail.com
Mon Nov 7 05:25:41 EST 2016


On Sun, Nov 6, 2016 at 9:09 AM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 06/11/16 01:44, Clayton Kirkwood wrote:
>> Looked all over, but haven't found the answer. If I have a (windows) program
>> which I wish to start, even shell scripts, and possibly capture the output
>> from, how do I do that?
>
> Others have already pointed you to the subprocess module.
> The documentation there includes several examples.
>
> On Windows it sometimes helps to start a program via the
> "start" command.

`start` is a cmd shell built-in command, so it requires passing
shell=True to subprocess.Popen. It allows more control over how a
process is started -- such as whether to use the current or a new
console, the window state, the process working directory, priority,
and CPU affinity -- and whether the shell should wait on the process.
Popen directly supports most of what `start` does, and otherwise you
can use os.startfile, which is generally safer than using the shell.

> start notepad.exe

Using `start` like this is typical in a batch file, to avoid waiting
for the command to exit. In contrast, Popen defaults to asynchronous
mode, and waiting requires the wait() or communicate() methods.

> start myfile.txt

`start` isn't generally necessary here. Both with and without `start`,
cmd tries to locate and execute (open) the file.

If the target is a batch file (i.e. .bat or .cmd), then cmd either
executes it in place or, if the `start` command is used, executes it
in a new shell via `cmd.exe /k`. Otherwise cmd first tries to execute
the target via CreateProcess(). If the latter fails, cmd tries
ShellExecuteEx(), using the default file association.

For example, the .py extension is usually associated with the ProgId
"Python.File". If the py launcher is installed, then the default
action for this ProgId is typically the template command
'C:\Windows\py.exe "%1" %*'. ShellExecuteEx substitutes the target
file and command-line arguments for the %1 and %* template parameters
and then calls CreateProcess.

The `start` command expands the set of possible targets to whatever
ShellExecuteEx supports, including directories and virtual targets.
For example:

    * Opening directories in Explorer
    * Opening `shell:` folders such as shell:UserProgramFiles
    * Executing "App Paths" commands registered under
      [HKCU|HKLM]\Software\Microsoft\Windows\CurrentVersion\App Paths

> If your program has a GUI however, accessing the output
> becomes much more difficult and may not even be
> possible. In that case you may need to resort
> to driving it programmatically via its API using
> a tool like pywin32 or ctypes.

The best-case scenario is an app that exports a COM IDispatch
interface for scripting, which you can access via PyWin32's win32com
module.


More information about the Tutor mailing list