[英]How would I store the shell command output to a variable in python?
Code:代码:
# cat mylinux.py
# This program is to interact with Linux
import os
v = os.system("cat /etc/redhat-release")
Output: Output:
# python mylinux.py
Red Hat Enterprise Linux Server release 7.6 (Maipo)
In the above output, the command output is displayed regardless of the variable I defined to store the output.在上面的output中,不管我定义的用来存储output的变量,都会显示命令output。
How to store the shell command output to a variable using os.system method only?如何仅使用 os.system 方法将 shell 命令 output 存储到变量中?
By using module subprocess
.通过使用模块
subprocess
。 It is included in Python's standard library and aims to be the substitute of os.system
.它包含在 Python 的标准库中,旨在成为
os.system
的替代品。 (Note that the parameter capture_output
of subprocess.run
was introduced in Python 3.7) (注意Python 3.7引入了
subprocess.run
的参数capture_output
)
>>> import subprocess
>>> subprocess.run(['cat', '/etc/hostname'], capture_output=True)
CompletedProcess(args=['cat', '/etc/hostname'], returncode=0, stdout='example.com\n', stderr=b'')
>>> subprocess.run(['cat', '/etc/hostname'], capture_output=True).stdout.decode()
'example.com\n'
In your case, just:在你的情况下,只是:
import subprocess
v = subprocess.run(['cat', '/etc/redhat-release'], capture_output=True).stdout.decode()
Update: you can split the shell command easily with shlex.split
provided by the standard library.更新:您可以使用标准库提供的
shlex.split
轻松拆分 shell 命令。
>>> import shlex
>>> shlex.split('cat /etc/redhat-release')
['cat', '/etc/redhat-release']
>>> subprocess.run(shlex.split('cat /etc/hostname'), capture_output=True).stdout.decode()
'example.com\n'
Update 2: os.popen
mentioned by @Matthias更新 2:
os.popen
提到的 os.popen
However, is is impossible for this function to separate stdout and stderr.但是,这个 function 不可能将 stdout 和 stderr 分开。
import os
v = os.popen('cat /etc/redhat-release').read()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.