输出由subprocess调用的命令行? [英] output the command line called by subprocess?
问题描述
我使用 subprocess.Popen
调用,在另一个问题中,我发现我一直误会Python是如何为命令行生成参数。
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?
示例代码: -
proc = subprocess.popen(....)
print "the commandline is %s" % proc.getCommandLine()
你会如何写 getCommandLine
?
推荐答案
你正在使用的Python。 在当前版本的Python3 中,arg保存在 proc.args
:
It depends on the version of Python you are using. In the current version of Python3, the arg is saved in proc.args
:
proc = subprocess.Popen(....)
print("the commandline is {}".format(proc.args))
.7,未保存 args
,它只是传递给其他函数,如 _execute_child
。所以,在这种情况下,获得命令行的最好的方法是保存它,当你有它:
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
请注意,如果您有参数的列表(例如 shlex.split )
,则可以使用未记录的函数 subprocess.list2cmdline $ c>恢复命令行字符串
cmd
$ c>:
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'
这篇关于输出由subprocess调用的命令行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!