代碼:
# cat mylinux.py
# This program is to interact with Linux
import os
v = os.system("cat /etc/redhat-release")
輸出:
# python mylinux.py
Red Hat Enterprise Linux Server release 7.6 (Maipo)
在上面的輸出中,無論我為存盤輸出定義的變數如何,都會顯示命令輸出。
如何僅使用 os.system 方法將 shell 命令輸出存盤到變數中?
uj5u.com熱心網友回復:
通過使用模塊subprocess。它包含在 Python 的標準庫中,旨在替代os.system. (注意引數capture_outputofsubprocess.run在 Python 3.7 中引入)
>>> 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'
在您的情況下,只需:
import subprocess
v = subprocess.run(['cat', '/etc/redhat-release'], capture_output=True).stdout.decode()
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'
更新 2:os.popen@Matthias 提到
然而,這個函式是不可能分離 stdout 和 stderr 的。
import os
v = os.popen('cat /etc/redhat-release').read()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467388.html
標籤:Python python-3.x linux 贝壳 命令
上一篇:比較檔案Unix
