簡體   English   中英

在python中調用外部命令並輸出到文件

[英]Call an external command in python and output to file

所以我在如何從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

您可以從os使用system

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

寫入命令的輸出可以通過“>”完成。 如果要追加而不是覆蓋文件,可以使用“>>”。

這將執行您的要求:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM