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 ''?

ealeon
  • 12,074
  • 24
  • 92
  • 173

2 Answers2

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'"]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • is the behavior OS independent? – Bleeding Fingers Oct 01 '13 at 15:49
  • @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*. – Martijn Pieters Oct 01 '13 at 15:53
1

maybe

python test.py blah="'blah'"
yakiang
  • 1,608
  • 1
  • 16
  • 17