为了账号安全,请及时绑定邮箱和手机立即绑定

在 python 中调用外部命令并输出到文件

在 python 中调用外部命令并输出到文件

心有法竹 2022-09-06 16:00:46
所以我在如何从python调用外部命令上发现了这一点,但是我如何使用此方法,而是将命令的输出输出输出到外部文件中。所以从本质上讲,我需要将命令的输出存储为文本文件。这可能吗?我找不到太多关于如何做到这一点的信息,我发现的那些还不清楚这是我当前的代码,但它只是在屏幕上显示输出,我不知道如何将其存储为文件    #!/usr/bin/python## get subprocess module import subprocess## call date command ##p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)## Talk with date command i.e. read data from stdout and stderr. Store this info in tuple #### Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.  #### Wait for process to terminate. The optional input argument should be a string to be sent to the child process, #### or None, if no data should be sent to the child.(output, err) = p.communicate()## Wait for date to terminate. Get return returncode ##p_status = p.wait()print "Command output : ", outputprint "Command exit status/return code : ", p_statu
查看完整描述

2 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

您可以从操作系统使用系统

import os
os.system("ls -l > file.txt")

写入命令的输出可以通过“>”来完成。如果要追加而不是覆盖文件,可以使用“>>”。


查看完整回答
反对 回复 2022-09-06
?
杨魅力

TA贡献1811条经验 获得超6个赞

这将完成您所要求的操作:

import subprocesswith open ('date.txt', 'w') as file :
    subprocess.Popen ('date', stdout = file)


查看完整回答
反对 回复 2022-09-06
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号