Python 输出子进程调用的命令行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14836947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
output the command line called by subprocess?
提问by Brian Postow
I'm using the subprocess.Popencall, and in another question I found out that I had been misunderstanding how Python was generating arguments for the command line.
我正在使用subprocess.Popen调用,在另一个问题中我发现我一直误解 Python 如何为命令行生成参数。
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?
你会怎么写getCommandLine?
采纳答案by unutbu
It depends on the version of Python you are using. In Python3.3, the arg is saved in proc.args:
这取决于您使用的 Python 版本。在 Python3.3 中,arg 保存在proc.args:
proc = subprocess.Popen(....)
print("the commandline is {}".format(proc.args))
In Python2.7, the argsnot 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:
在Python2.7,在args没有保存,它只是传递到像其他功能_execute_child。因此,在这种情况下,获取命令行的最佳方法是在拥有时保存它:
proc = subprocess.Popen(shlex.split(cmd))
print "the commandline is %s" % cmd
Note that if you have the listof arguments (such as the type of thing returned by shlex.split(cmd), then you can recover the command-line string, cmdusing the undocumented function subprocess.list2cmdline:
请注意,如果您有参数列表(例如由 返回的事物类型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'
回答by Brian Postow
The correct answer to my question is actually that there ISno 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.
我的问题的正确答案实际上是没有命令行。子进程的重点是它通过 IPC 完成所有工作。list2cmdline 与预期的一样接近,但实际上最好的做法是查看“args”列表,并且只知道在被调用程序中它将是 argv。

