Mike H-R
Mike H-R

Reputation: 7825

how to call subprocess.check_call with a quoted argument on windows?

subprocess.check_call(["C:\\cygwin\\bin\\bash", "-c", '"echo hello; echo goodbye"'], shell=True)

on windows, returns:

/usr/bin/bash: echo hello; echo goodbye: command not found

however, running:

C:\cygwin\bin\bash -c "echo hello; echo goodbye"

gives the expected output:

hello
goodbye

How do I get around this?

Upvotes: 0

Views: 231

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34280

A Windows process has to parse its own argument list from the command line that gets passed to CreateProcess. In contrast, POSIX systems use the exec and spawn functions, which take an already parsed argv array.

On Windows, subprocess.Popen calls subprocess.list2cmdline to convert a list to a command-line string. This assumes VC++ parsing rules, so a literal quote character will be escaped as \". If Cygwin uses different rules from VC++, just pass args as a string instead of a list. For example:

subprocess.check_call(r'C:\cygwin\bin\bash -c "echo hello; echo goodbye"')

You can also explicitly provide the executable.

subprocess.check_call('bash -c "echo hello; echo goodbye"', 
                      executable=r'C:\cygwin\bin\bash.exe')

It gets passed to CreateProcess as the lpApplicationName parameter.

Upvotes: 2

Related Questions