我正在使用 subprocess.Popen
调用,在另一个问题中我发现我一直误解 Python 是如何为命令行生成参数的。
我的问题
有没有办法找出实际的命令行是什么?
示例代码:-
proc = subprocess.popen(....)
print "the commandline is %s" % proc.getCommandLine()
你会怎么写 getCommandLine
?
最佳答案
这取决于您使用的 Python 版本。 In Python3.3 , arg 保存在 proc.args
:
proc = subprocess.Popen(....)
print("the commandline is {}".format(proc.args))
在 Python2.7 中,the args
not saved ,它只是传递给其他函数,如 _execute_child
。因此,在这种情况下,获取命令行的最佳方法是在拥有它时保存它:
proc = subprocess.Popen(shlex.split(cmd))
print "the commandline is %s" % cmd
注意如果你有list的参数(比如shlex.split(cmd)
返回的东西的类型,那么你可以恢复命令行字符串,cmd
使用未记录的函数 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'
关于python - 输出子进程调用的命令行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836947/