[python-win32] win32process.CreateProcess alternative that takes an array

Moore, Paul Paul.Moore@atosorigin.com
Mon, 7 Apr 2003 09:53:40 +0100


From: Christopher Armstrong [mailto:radix@twistedmatrix.com]
> Twisted uses win32process.CreateProcess for its Process running
> on win32. This is bad, because CreateProcess needs a string
> - right now we just to a " ".join on the arguments to the
> program, but obviously that totally breaks when some of the
> arguments have spaces in them. Is there an alternative to
> CreateProcess that takes a list of arguments rather than a
> string? Is there even an unwrapped win32 call that takes an
> array? I really don't want to mess with trying to automatically
> quote the arguments that have spaces.

I don't believe there is. The fundamental construct in Windows
is the command line. CreateProcess passes a command line to
the process, and the process retrieves that command line via
GetCommandLine. All splitting of this command line into a set of
arguments is handled entirely by user code. It's a fundamental
difference between the Unix approach and the Windows approach.
(You can argue endlessly over which is better, but that's
fruitless - it's just a fact you have to deal with.)

Creating a command line from an argv list in such a way that a
user program will recreate the same argv list is dependent on the
code used by the C runtime of the program called, and hence is
impossible in complete generality, although it's not hard for 99%
of cases. As long as you don't care much about what happens to
an argument like <hello\\"\'\\""" ""\ \\ '\'there> you're going
to be OK :-)

The code in Python for os.exec* (I believe) just punts to the
CRT with which Python was built, and so isn't much use. For a
comprehensive (and complex) answer, I believe TCL implements a
cross-platform exec call.

Alternatively, rethink the higher level - why are you joining a
list of arguments in the first place? Could you respecify the
higher level to not require the user to pass a list, but pass a
command line on Windows? I believe that the key argument for argv
in Unix is security - you don't go through the shell's (complex
and powerful) command line splitting routines. On Windows, that
argument is reversed - by supplying a command line, you don't go
through an error-prone process of combining and resplitting.

Hope this helps (but it probably doesn't :-))
Paul.