Python sys.argv to preserve ' ' or ""
Asked Answered
F

2

10

terminal:

python test.py blah='blah'

in test.py

print sys.argv
['test.py', 'blah=blah'] <------------ 

How can blah arg preserve its '' OR
Is there a way to know if an arg is wrap with either "" or ''?

Fredericksburg answered 1/10, 2013 at 15:31 Comment(5)
That's not something Python controls.. That is your shell removing the quotes before passing it on to Python.Circassia
It’s the shell that ‘strips’ the quotes; use python test.py "blah='blah'" instead.Sleep
This appears to be an XY Problem. Why do you want the quotes?Murcia
If you need your application to accept free-form text instead of the symbolic-ish data from command line arguments, it'll likely be easier to read it from stdin.Deppy
please mention the OS or the shell you are usingJavier
C
13

Your shell removes the quotes before invoking Python. This is not something Python can control.

Add more quotes:

python test.py "blah='blah'"

which can also be placed anywhere in the argument:

python test.py blah="'blah'"

or you could use backslash escapes:

python test.py blah=\'blah\'

to preserve them. This does depend on the exact shell you are using to run the command.

Demo on bash:

$ cat test.py 
import sys
print sys.argv
$ python test.py blah='blah'
['test.py', 'blah=blah']
$ python test.py "blah='blah'"
['test.py', "blah='blah'"]
$ python test.py blah="'blah'"
['test.py', "blah='blah'"]
$ python test.py blah=\'blah\'
['test.py', "blah='blah'"]
Circassia answered 1/10, 2013 at 15:33 Comment(2)
is the behavior OS independent?Javier
@hus787: Very much so. It depends on the shell implementation. On windows, the cmd console quoting uses different rules from the bash shell. I have little experience with tsh or zsh but they may well use different rules again.Circassia
R
1

maybe

python test.py blah="'blah'"
Rattat answered 1/10, 2013 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.