Home > database >  CreateProcess: space in a python command passed with -c
CreateProcess: space in a python command passed with -c

Time:12-05

I am trying to port muon (a C99 implementation of meson) to Windows, and i have some problem with one of its unit tests. This unit test calls python3 with an array of C string, this array being:

"-c"
"print("some output")"

Note that this array can be any python script passed to the interpreter.

So I call CreateProcess() with lpApplicationName being the string "C:\Documents\msys2\mingw64\bin/python3.exe" and lpCommandLine being "-c print(\"some output\")" (I have prepended \ before each " that I find in the string in the above array)

My problem is the space that is in the print() function. I get this error message:

err failed to run python3:   File "<string>", line 1
    print("some
          ^
SyntaxError: unterminated string literal (detected at line 1)

I can't find a way to modify the string print(\"some output\") so that lpCommandLine is correctly built.

Does someone have an idea how to do this ?

thank you

CodePudding user response:

If you're trying to pass a string with a space in it as a command-line argument to Python, you need to enclose the string in quotation marks so that the shell knows it's a single argument.

For example, you could try passing the following command line to Python:

"-c" "print(\"some output\")"

This way, the shell will interpret the entire string "print("some output")" as a single argument, and Python will be able to interpret it correctly.

You may also need to escape the quotation marks in the string so that the shell doesn't interpret them as delimiters for the command-line arguments. To do this, you can add a backslash () before each quotation mark in the string, like this:

"-c" "print(\\"some output\\")"

This should allow you to pass a string with a space in it as a command-line argument to Python without any issues.

It's also worth mentioning that in the C99 implementation of Meson, the muon program uses the execvp function to spawn a new process and run a command with a list of arguments. This is a better way to run a command with arguments than using CreateProcess, because it allows you to pass the arguments as an array of strings, rather than as a single string that needs to be manually parsed.

For example, instead of calling CreateProcess with lpApplicationName set to the path of the Python interpreter and lpCommandLine set to the string "-c print("some output")", you could use the execvp function to run the Python interpreter with the following arguments:

argv[0] = "python3"
argv[1] = "-c"
argv[2] = "print(\"some output\")"

This way, you don't need to worry about escaping or quoting the arguments, because the execvp function will take care of that for you.

I hope this helps!

CodePudding user response:

Have you tried "print('some output')" or 'print("some output")'?

  • Related