5

Possible Duplicate:
Full command line as it was typed

sys.argv is already a parsed array, losing double quotes, double spaces and maybe even tab characters (it all depends on the OS/shell, of course).

How can I access the original string before parsing?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Berry Tsakala
  • 15,313
  • 12
  • 57
  • 80

3 Answers3

4

Shortly, you don't.

Long: on Unix command line is parsed by the calling program and by the time python starts you already have the command line parsed.

PS. On Windows it is possible, but I suppose you are looking for a general response.

wim
  • 338,267
  • 99
  • 616
  • 750
sorin
  • 161,544
  • 178
  • 535
  • 806
-1

You can't do that explicitly because, this is how a shell passes the arguments to a program.

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
-1

The sys.argv is all Python got. The shell processed the filename generation (globs), parameter (variable) expansion, quotes, and word splitting before passing the arguments to the Python process (in Unix; in Windows it's the startup actually parsing it, but for portability, you can't rely on that).

However, remember that POSIX shell quoting rules allow passing any characters you may want (except NUL bytes that terminate strings).

Compare starting a process from Python using subprocess.call with or without the shell argument set. With shell=False the list of strings is what comes up in the sys.argv in the started process (starting with the script path; parameters processed by Python itself are removed) while with shell=True the string is passed to the shell which interprets it according to its own rules.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • 2
    "The sys.argv is exactly what you got" is not true. The CPython executable parses the command line and populates `sys.argv`, according to certain rules. For instance `python -c cmd`: `cmd` will not be in `sys.argv`. – Dr. Jan-Philip Gehrcke Feb 09 '15 at 18:02
  • @Jan-PhilipGehrcke: Formally, you are correct. But I don't think it is relevant here. For script, it will be what you've got (with the script name expanded) and command-line commands are not very useful due to how it's almost impossible to cram python on single line. – Jan Hudec Feb 09 '15 at 20:33
  • 2
    You are right, but I use every opportunity to stress that command line arguments are so full of encoding/decoding, interpretation and re-interpretation, and all kinds of conversion on different levels, that I cannot really like a statement such as "is exactly what you got" :-). Found my down-vote a little too harsh now, but cannot remove it anymore, sorry. – Dr. Jan-Philip Gehrcke Feb 09 '15 at 21:28
  • @Jan-PhilipGehrcke: Ok, I rewrote it not to be so categorical and added some more information (note: edits allow voting again) – Jan Hudec Feb 10 '15 at 08:29