我想编写一个函数来执行 shell 命令并将其输出作为字符串返回,无论是错误还是成功消息。我只想得到与使用命令行相同的结果。
什么代码示例可以做这样的事情?
例如:
def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
网友回答:
这更容易,但仅适用于Unix(包括Cygwin)和Python2.7。
import commands
print commands.getstatusoutput('wc -l file')
它返回一个带有 (return_value, 输出) 的元组。
对于同时适用于 Python2 和 Python3 的解决方案,请改用该模块:subprocess
from subprocess import Popen, PIPE
output = Popen(["date"],stdout=PIPE)
response = output.communicate()
print response
网友回答:
在所有官方维护的 Python 版本中,最简单的方法是使用以下函数:subprocess.check_output
>>> subprocess.check_output(['ls', '-l'])
b'total 0n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 filesn'
check_output
运行仅将参数作为输入的单个程序。1 它返回的结果与打印到 .如果需要将输入写入 ,请跳到 或 部分。如果要执行复杂的 shell 命令,请参阅本答案末尾的注释。stdout
stdin
run
Popen
shell=True
该函数适用于所有官方维护的 Python 版本。但对于更新的版本,可以使用更灵活的方法。check_output
run
如果你使用的是 Python 3.5+,并且不需要向后兼容,官方文档建议将新函数用于大多数任务。它为模块提供了一个非常通用的高级 API。若要捕获程序的输出,请将标志传递给关键字参数。然后访问返回对象的属性:run
subprocess
subprocess.PIPE
stdout
stdout
CompletedProcess
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 filesn'
返回值是一个对象,所以如果你想要一个合适的字符串,你需要它。假设被调用的进程返回一个 UTF-8 编码的字符串:bytes
decode
>>> result.stdout.decode('utf-8')
'total 0n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 filesn'
如果需要,这一切都可以压缩为单行:
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 filesn'
如果要将输入传递给进程的 ,可以将对象传递给关键字参数:stdin
bytes
input
>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foonfoofoon'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoon'
您可以通过传递(捕获到 )或(捕获到)以及常规输出来捕获错误。如果要在进程返回非零退出代码时引发异常,可以传递 .(或者你可以检查上面的属性。当安全性不是问题时,您还可以通过传递来运行更复杂的 shell 命令,如本答案末尾所述。stderr=subprocess.PIPE
result.stderr
stderr=subprocess.STDOUT
result.stdout
run
check=True
returncode
result
shell=True
Python的更高版本进一步简化了上述内容。在 Python 3.7+ 中,上面的单行代码可以这样拼写:
>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 filesn'
与旧的做事方式相比,使用这种方式只会增加一点复杂性。但是现在,您几乎可以单独使用该函数执行任何需要做的事情。run
run
check_output
如果您使用的是旧版本的 Python,或者需要适度的向后兼容性,则可以使用上述简要描述的函数。它从Python 2.7开始就可用了。check_output
subprocess.check_output(*popenargs, **kwargs)
它采用与(见下文)相同的参数,并返回一个包含程序输出的字符串。本答案的开头有一个更详细的使用示例。在 Python 3.5+ 中,等效于使用 and 执行,只返回属性。Popen
check_output
run
check=True
stdout=PIPE
stdout
您可以传递以确保错误消息包含在返回的输出中。当安全性不是问题时,您还可以通过传递来运行更复杂的 shell 命令,如本答案末尾所述。stderr=subprocess.STDOUT
shell=True
如果需要从流程通过管道传输或将输入传递给流程,则无法胜任任务。在这种情况下,请参阅以下示例。stderr
check_output
Popen
Popen
如果您需要深度向后兼容性,或者如果您需要比 or 提供更复杂的功能,则必须直接使用对象,这些对象封装了子进程的低级 API。check_output
run
Popen
构造函数接受不带参数的单个命令,或者接受包含命令作为其第一项的列表,后跟任意数量的参数,每个参数作为列表中的单独项。 可以帮助将字符串解析为格式适当的列表。 对象还接受进程 IO 管理和低级配置的大量不同参数。Popen
shlex.split
Popen
发送输入和捕获输出,几乎总是首选方法。如:communicate
output = subprocess.Popen(["mycmd", "myarg"],
stdout=subprocess.PIPE).communicate()[0]
或
>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE,
... stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo
如果设置 ,还允许您通过以下方式将数据传递给进程:stdin=PIPE
communicate
stdin
>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... stdin=subprocess.PIPE)
>>> out, err = p.communicate('foonfoofoon')
>>> print out
foofoo
请注意 Aaron Hall 的回答,该答案表明在某些系统上,您可能需要将 、 和 all 设置为 (或 ) 才能开始工作。stdout
stderr
stdin
PIPE
DEVNULL
communicate
在极少数情况下,您可能需要复杂的实时输出捕获。Vartec的回答提出了一条前进的道路,但如果不谨慎使用,其他方法很容易陷入僵局。communicate
与上述所有函数一样,当安全性不是问题时,您可以通过传递 .shell=True
1. 运行 shell 命令:shell=True
参数
通常,每次调用 、 或构造函数都会执行单个程序。这意味着没有花哨的bash式管道。如果要运行复杂的 shell 命令,可以传递 ,这三个函数都支持。例如:run
check_output
Popen
shell=True
>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376n'
但是,这样做会引起安全问题。如果您正在做的不仅仅是轻量级脚本,则最好单独调用每个进程,并将每个进程的输出作为输入传递给下一个进程,通过
run(cmd, [stdout=etc...], input=other_output)
或
Popen(cmd, [stdout=etc...]).communicate(other_output)
直接连接管道的诱惑力很强;抵制它。否则,您可能会看到死锁或不得不做这样的黑客操作。
网友回答:
我遇到了同样的问题,但想出了一种非常简单的方法:
import subprocess
output = subprocess.getoutput("ls -l")
print(output)
注意:此解决方案特定于 Python3,在 Python2 中不起作用subprocess.getoutput()
模板简介:该模板名称为【编写函数来执行 shell 命令并将其输出作为字符串返回,得到与使用命令行相同的结果。】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。