Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output the command line called by subprocess?

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 ?

like image 223
Brian Postow Avatar asked Feb 12 '13 16:02

Brian Postow


People also ask

How do I get the output of a subprocess call?

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 ...

How do I run a Python command line in subprocess?

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.

What does Python subprocess call return?

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.


2 Answers

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'
like image 174
unutbu Avatar answered Oct 09 '22 05:10

unutbu


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.

like image 7
Brian Postow Avatar answered Oct 09 '22 05:10

Brian Postow