1

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]))
Stpn
  • 6,202
  • 7
  • 47
  • 94

2 Answers2

7

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"
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • The input is made by users and is always different. Or maybe I don't understand something..? – Stpn Mar 06 '12 at 19:58
  • a semicolon inside a quote is okay. what happened was that the first quote closed the arg, and the semicolon made the shell execute your command. how are you getting the user input? – Not_a_Golfer Mar 06 '12 at 20:01
  • well it's being sent from a website... I guess I can filter everything on the web-side through regex, but was wondering if there is a simpler way to do that.. – Stpn Mar 06 '12 at 20:04
  • would this help? `>>> re.escape('hello "world"') 'hello\\ \\"world\\"'` – Not_a_Golfer Mar 06 '12 at 20:08
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.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292