Wicelo
Wicelo

Reputation: 2426

Why two same string but concatenated differently have different results in shell context called with python?

I want to start a cygwin command from my python script and my command is in the variable params. I have multiple ways to write the string :

import os
import subprocess

params = r'"C:\cygwin64\bin\bash.exe" --login -c ' + r"""'ls "C:\Users"'"""

print(subprocess.check_output(params, shell=True))

This works just fine, however this :

import os
import subprocess

params = r"""'C:\cygwin64\bin\bash.exe' --login -c 'ls "C:\Users"'"""

print(subprocess.check_output(params, shell=True))

Returns non-zero exit status 1 while it is supposed to be exactly the same string. To check the difference I run this script :

print(repr(r"""'C:\cygwin64\bin\bash.exe' --login -c 'ls "C:\Users"'"""))
print(repr(r'"C:\cygwin64\bin\bash.exe" --login -c ' + r"""'ls "C:\Users"'"""))

Returns :

'\'C:\\cygwin64\\bin\\bash.exe\' --login -c \'ls "C:\\Users"\''
'"C:\\cygwin64\\bin\\bash.exe" --login -c \'ls "C:\\Users"\''

I'm not sure how to interpret that frankly speaking neither do I understand how to fix my monolitic string.

Upvotes: 1

Views: 52

Answers (1)

John Kugelman
John Kugelman

Reputation: 361730

The first string wraps bash.exe in double quotes:

"C:\cygwin64\bin\bash.exe"

The second one wraps it in single quotes.

'C:\cygwin64\bin\bash.exe'

Double quotes is what you want. Or no quotes, since the path has no spaces.

params = r""""C:\cygwin64\bin\bash.exe" --login -c 'ls "C:\Users"'"""
params = r"""C:\cygwin64\bin\bash.exe --login -c 'ls "C:\Users"'"""

Upvotes: 1

Related Questions