3

I'm trying to run a python script using PowerShell. In that python script I try to use a command line argument which includes double quotes and whitespace, which does not work properly. I suspect it to be an issue with PowerShell.

The (simplified) python script looks like this:

import sys
print(sys.argv[1])

The following calls and outputs show the problem

python script.py --arg=foo
--arg=foo

python script.py --arg='\"foo\"'
--arg="foo"

python script.py --arg='\"fo o\"'
--arg="fo

But what I need in the end is

--arg="fo o"

It strips away everything after the whitespace. I tested the same script in a Linux bash where it worked (with double quotes around the foo). This seems not to be a python issue but a PowerShell problem, can anyone help me? In the end I want to have a full JSON-String as the argument.

7
  • Have you tried escaping the whitespace with \? Commented Mar 9, 2018 at 7:59
  • Yes. Then I get --arg="fo\ Commented Mar 9, 2018 at 8:13
  • PowerShell version? OS? Commented Mar 9, 2018 at 8:19
  • OK, I found one way to do it: python .\script.py '--arg="""fo o"""' I get --arg="fo o". But seriously. Microsoft. wt...? Commented Mar 9, 2018 at 8:24
  • Alternatively python .\script.py '"--arg=\"fo o\""'. The outermost set of quotes defines the token as a string for PowerShell. The outer set of double quotes is for passing the entire token with the inner (escaped) double quotes to the Python process. With that said, why are you trying to pass arguments like that instead of useing argparse? Commented Mar 9, 2018 at 9:15

2 Answers 2

4

9 Month no answer. Current workaround is to escape " with \".

Here is the bug: https://github.com/PowerShell/PowerShell/issues/1995

Sign up to request clarification or add additional context in comments.

2 Comments

You deserve a medal
Thanks for this sir!!! OMG I have been searching for this a lot
2

Escaping " with '\`' (backslash + backtick) also works (I cannot include the backtick here in the code-style markdown because I don't know how to escape it... ironic).

Please note that the whole argument with the escaped double quotes has to be encapsulated in the double quotes as well. Putting single quotes around it will not work.

Source: http://www.rlmueller.net/PowerShellEscape.htm

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.