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

所以我在如何从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 : ", output

print "Command exit status/return code : ", p_statu


心有法竹
浏览 166回答 2
2回答

陪伴而非守候

您可以从操作系统使用系统。import os os.system("ls -l > file.txt")写入命令的输出可以通过“>”来完成。如果要追加而不是覆盖文件,可以使用“>>”。

杨魅力

这将完成您所要求的操作:import subprocesswith open ('date.txt', 'w') as file :     subprocess.Popen ('date', stdout = file)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python