Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.argv to preserve ' ' or ""

Tags:

python

sys

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

like image 765
ealeon Avatar asked Oct 01 '13 15:10

ealeon


1 Answers

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'"]
like image 146
Martijn Pieters Avatar answered Sep 16 '22 20:09

Martijn Pieters