输出子进程调用的命令行? [英] output the command line called by subprocess?

查看:26
本文介绍了输出子进程调用的命令行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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.3 中,参数保存在 <代码>proc.args:

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

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

<小时>

注意,如果你有list参数(比如shlex.split(cmd)返回的东西类型,那么你可以恢复命令行字符串,cmd 使用未公开的函数 subprocess.list2cmdline:


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'

这篇关于输出子进程调用的命令行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆