0

I have a string containing arguments e.g python program_name.py arg1 arg2. I want to add an argument in a certain index, e.g 2, so, as in array indexing, it should result like this: python program_name.py my_argument arg1 arg2.

In this case, there is no problem, I can just use:

s = "python program_name.py arg1 arg2"
l = s.split()
l.insert(2, "my_argument")
print "My final result:", ' '.join(l)

BUT, what happens if one of the arguments includes spaces? say a string argument like this Wow, this is a long argument. When using it in the command like it obviously is wrapped with ", how can I, then, accomplish my mission?

Example string: python program_name.py "My long string argument" another_one and_another_one

how do I end up with python program_name.py my_argument "My long string argument" another_one and_another_one ?

Zach P
  • 1,731
  • 11
  • 16
  • 1
    How did you get the arguments string? sys.argv is already split up for you, just insert to that list, wrap all elements in double-quotes and join. – CDahn May 31 '16 at 13:54
  • I would just put quotes around all arguments, and not worry about it, but this is more correct: http://stackoverflow.com/questions/35817/how-to-escape-os-system-calls-in-python (use shlex.quote or pipes.quote, depending on python version) – Kenny Ostrom May 31 '16 at 13:57
  • The duplicate looks the same as your post, If it does not answer your post, please [edit] the question. – Bhargav Rao May 31 '16 at 14:05
  • 1
    @BhargavRao It does answer! Thank you and sorry for the duplicate, I did not find that question when I searched – Zach P May 31 '16 at 14:05

0 Answers0