I'm using the subprocess.Popen
call, and in another question I found out that I had been misunderstanding how Python was generating arguments for the command line.
My Question
Is there a way to find out what the actual command line was?
Example Code :-
proc = subprocess.popen(....)
print "the commandline is %s" % proc.getCommandLine()
How would you write getCommandLine
?
communicate() #Another way to get output #output = subprocess. Popen(args,stdout = subprocess. PIPE). stdout ber = raw_input("search complete, display results?") print output #... and on to the selection process ...
Python Subprocess Run Function The subprocess. run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.
Return Value of the Call() Method from Subprocess in Python The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.
It depends on the version of Python you are using. In Python3.3, the arg is saved in proc.args
:
proc = subprocess.Popen(....)
print("the commandline is {}".format(proc.args))
In Python2.7, the args
not saved, it is just passed on to other functions like _execute_child
. So, in that case, the best way to get the command line is to save it when you have it:
proc = subprocess.Popen(shlex.split(cmd))
print "the commandline is %s" % cmd
Note that if you have the list of arguments (such as the type of thing returned by shlex.split(cmd)
, then you can recover the command-line string, cmd
using the undocumented function subprocess.list2cmdline
:
In [14]: import subprocess
In [15]: import shlex
In [16]: cmd = 'foo -a -b --bar baz'
In [17]: shlex.split(cmd)
Out[17]: ['foo', '-a', '-b', '--bar', 'baz']
In [18]: subprocess.list2cmdline(['foo', '-a', '-b', '--bar', 'baz'])
Out[19]: 'foo -a -b --bar baz'
The correct answer to my question is actually that there IS no command line. The point of subprocess is that it does everything through IPC. The list2cmdline does as close as can be expected, but in reality the best thing to do is look at the "args" list, and just know that that will be argv in the called program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With