Raw command line arguments

Dave Angel davea at ieee.org
Fri Apr 24 06:35:30 EDT 2009


Enchanter wrote:
> How to pass the raw command line arguments to the python?
>
> Such as:
>
>      mypython.py  txt -c "Test Only" {Help}
>
>
> The arguments I hope to get is:
>
>               txt -c "Test Only" {Help}               -- Keep the
> quotation marks in the arguments.
>
>
>   
As Chris has said, the shell (and the C runtime) preprocesses the line 
before python ever sees it.  However, if you're on Windows, there is a 
function GetCommandLine, located in Kernel32.dll, which I *think* keeps 
the raw bytes typed by the user.  Clearly, that would be a non-portable 
answer, but here's some samples if you want to try it:

import sys
print sys.argv            #this one loses the quotes

import ctypes
#print ctypes.windll.kernel32.GetModuleHandleA
#hdl = ctypes.windll.kernel32.GetModuleHandleA(0)
#print hdl

func = ctypes.windll.kernel32.GetCommandLineA
print func
func.restype = ctypes.c_char_p

cmd = ctypes.windll.kernel32.GetCommandLineA()
print cmd           #this one gives a single string, such as the one below:

"C:\ProgFiles\Python26\python.exe"  
"M:\Programming\Python\sources\dummy\args.py"  txt -c "Test Only" (Help)

If you do go this route, but still want to be portable, you could make 
this code conditional on platform, then document the user to use 
escaping on Linux and Apple, while you do this approach for Windows.





More information about the Python-list mailing list