gpt4 book ai didi

python - 将 os.system() 输出重定向到 .txt 文件

转载 作者:行者123 更新时间:2023-11-28 22:34:37 25 4
gpt4 key购买 nike

我是 Python 新手。我有 Unix 命令列表 ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat/proc/meminfo","ls -l/dev") 我想运行它们并将整个输出重定向到 .txt 文件。我搜索了很多但没有找到合适的解决方案,或者我理解错误。

我可以使用这个 for 循环在 stdout 上获取输出,但我无法重定向到文件。

def commandsoutput():
command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")

for i in command:
print (os.system(i))

commandsoutput()

最佳答案

os.system 返回命令的退出代码,而不是它的输出。它也被弃用了。

改用subprocess:

import subprocess

def commandsoutput():
command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")

with open('log.txt', 'a') as outfile:
for i in command:
subprocess.call(i, stdout=outfile)

commandsoutput()

关于python - 将 os.system() 输出重定向到 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38830596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com