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.

aL_eX
  • 1,453
  • 2
  • 15
  • 30
Iarwa1n
  • 460
  • 3
  • 12
  • Have you tried escaping the whitespace with \? – Mathias R. Jessen Mar 09 '18 at 07:59
  • Yes. Then I get --arg="fo\ – Iarwa1n Mar 09 '18 at 08:13
  • PowerShell version? OS? – user4003407 Mar 09 '18 at 08:19
  • OK, I found one way to do it: `python .\script.py '--arg="""fo o"""'` I get `--arg="fo o"`. But seriously. Microsoft. wt...? – Iarwa1n Mar 09 '18 at 08: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`](https://docs.python.org/2/howto/argparse.html)? – Ansgar Wiechers Mar 09 '18 at 09:15
  • Possible duplicate of [How to pass in a string with spaces into PowerShell?](https://stackoverflow.com/questions/28311191/how-to-pass-in-a-string-with-spaces-into-powershell) – Yasushi Shoji Mar 09 '18 at 09:27
  • @YasushiShoji Not a duplicate, b/c running the command from PowerShell instead of CMD requires an additional set of quotes. – Ansgar Wiechers Mar 09 '18 at 11:20

2 Answers2

4

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

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

user2174835
  • 357
  • 3
  • 11
1

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

Gene M
  • 1,136
  • 1
  • 10
  • 16