简体   繁体   English

将终端输出写入文件

[英]writing terminal output to file

On my machine, I have some software which takes commands in the terminal and returns a list of values. 在我的机器上,我有一些软件可以在终端中接收命令并返回值列表。

To run it, I have to type something like: 要运行它,我必须输入以下内容:

pdv -t filename

I am trying to run it as part of a python programme. 我正在尝试将其作为python程序的一部分运行。 When I run the following: 当我运行以下命令时:

os.system('pdv -t %s' % (epoch_name))

then I get the values that I desire returned to my terminal (where epoch_name is the variable name for the filename). 然后我得到想要返回到终端的值(其中epoch_name是文件名的变量名)。 But when I try to write the result to a file: 但是,当我尝试将结果写入文件时:

os.system('pdv -t %s % "(epoch_name)" > 123.txt')

the file 123.txt is produced but it is empty. 产生了文件123.txt,但它为空。

I know that I am misplacing the " and/or ' characters, but I can't figure out where they should go. 我知道我放错了“和/或'字符,但是我不知道它们应该去哪里。

Any help would be gratefully received! 任何帮助将不胜感激!

You can use subprocess.call, with the stdout keyword argument: 您可以使用带有stdout关键字参数的subprocess.call:

import subprocess

cmd = ['ls', '-l']

with open('output.txt', 'w') as out:
    return_code = subprocess.call(cmd, stdout=out)

I believe this does what you want. 我相信这是您想要的。 Argument to os.system() should be a string representing command to the OS. os.system()参数应该是代表操作系统命令的字符串。

os.system('pdv -t %s > 123.txt' % epoch_name)

There is subprocess module, which may worth look into if you are planning to process the output further in python. subprocess模块,如果您打算用python进一步处理输出,可能值得研究。

Its better to use subprocess module that os.system 最好使用os.system的子流程模块

import subprocess
subprocess.call(['pdv', '-t', filename, '>', dest_file_name])
from subprocess import Popen
proc = Popen(['pdv', '-t', epoch_name], stdout = open('123.txt', 'w'))

See if the command script is available to you. 查看命令script是否可用。 It might do what you need. 它可能会满足您的需求。

Or you can use sys.stdout check this document from DiveIntoPython or the discussion here if it helps you out. 或者,您也可以使用sys.stdoutDiveIntoPython中检查此文档,或者在这里进行讨论以帮助您。

import sys

print 'Dive in'
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock
print 'This message will be logged instead of displayed'
sys.stdout = saveout
fsock.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM