Python转义sys argv中的特殊字符 [英] Python escape special characters in sys argv

查看:43
本文介绍了Python转义sys argv中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个采用 sys.argv 的脚本,输入可能包含特殊字符(分号).我只需要输入作为字符串,但分号把一切都搞砸了..

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..

我有:

def myscript(text)
    print text


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

我尝试:

>>  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""

我明白了:

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

我试过了:

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

推荐答案

这不是 python 的问题,你需要在调用 shell 中对其进行转义.只需将引号转义为 \" 并将分号转义为 \;.

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"

这篇关于Python转义sys argv中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆