Python escape special characters in sys argv

北城余情 提交于 2020-01-05 07:04:05

问题


I have a script that takes sys.argv and the input may contain special characters (semicolon). I just need the input as string, but semicolon messes everything up..

I have:

def myscript(text)
    print text


a = myscript(sys.argv[1])
print a

I try:

>>  python script.py "With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering" from la grippe; grippe being then a new word in St. Petersburg""

I get:

'With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering'
None
bash: grippe: command not found

I just want to get the whole string into the script no matter what is inside it..

I tried:

a = myscript(repr(sys.argv[1]))
a = myscript(str(sys.argv[1]))

回答1:


it's not a matter of python, you need to escape it in the calling shell. simply escape quotes as \" and semicolons as \;.

$ python testme.py "With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering\" from la grippe; grippe being then a new word in St. Petersburg\""

With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering" from la grippe; grippe being then a new word in St. Petersburg"



回答2:


This is not a python issue, it's a bash issue. Bash thinks the ; (semicolon) is separating a new bash command. You need to escape it.



来源:https://stackoverflow.com/questions/9590838/python-escape-special-characters-in-sys-argv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!