views:

291

answers:

6

I want to get the full command line as it was typed.

This:

" ".join(sys.argv[:])

doesn't work here (deletes double quotes). Also I prefer not to rejoin something that was parsed and splited.

Any ideas?

Thank you in advance.

+10  A: 

In a unix environment, this is not generally possible...the best you can hope for is the command line as passed to your process.

Because the shell (essentially any shell) may munge the typed command line in several ways before handing it to the OS to for execution.

dmckee
+19  A: 

You're too late. By the time that the typed command gets to Python your shell has already worked its magic. For example, quotes get consumed (as you've noticed), variables get interpolated, etc.

Martin Carpenter
+1  A: 

On Windows subprocess.list2cmdline() might help.

J.F. Sebastian
+4  A: 

As mentioned, this probably cannot be done, at least not reliably. In a few cases, you might be able to find a history file for the shell (e.g. - "bash", but not "tcsh") and get the user's typing from that. I don't know how much, if any, control you have over the user's environment.

Roboprog
Even in the .history, some processing has been applied (! substitution at a minimum...). +1 for cleverness, though. Nice thought.
dmckee
I believe that Bash, be default, doesn't write to the .history file except at the end of a session, so this doesn't work either.
ephemient
+1  A: 

If you're on linux, I'd suggest monkeying with the ~/.bash_history or the shell history command, although I believe the command must finish executing before it's added to the shell history.

I started playing with:

import popen2
x,y = popen2.popen4("tail ~/.bash_history")
print x.readlines()

but I'm getting weird behavior where the shell doesn't seem to be completely flushing to the .bash_history file

The flush-timing issue was pointed out to me as well :-(
Roboprog
A: 

On linux there is /proc//cmdline that is in format of argv[] (ie. there is 0x00 between all the lines and you can't really know how many strings there are since you don't get the argc; though you will know it when the file runs out of data ;).

You can be sure that that commandline is already munged too since all escaping/variable filling is done and parameters are nicely packages (no extra spaces between parameters etc.).

Pasi Savolainen