将 subprocess.Popen 输出附加到文件?

append subprocess.Popen output to file?(将 subprocess.Popen 输出附加到文件?)
本文介绍了将 subprocess.Popen 输出附加到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以成功地将我的输出重定向到一个文件,但这似乎覆盖了文件的现有数据:

I can successfully redirect my output to a file, however this appears to overwrite the file's existing data:

import subprocess
outfile = open('test','w') #same with "w" or "a" as opening mode
outfile.write('Hello')
subprocess.Popen('ls',stdout=outfile)

将从文件中删除 'Hello' 行.

will remove the 'Hello' line from the file.

我想一种解决方法是将输出作为字符串或其他东西存储在其他地方(不会太长),然后用 outfile.write(thestring) 手动附加它 - 但我是想知道我是否在模块中遗漏了一些有助于实现这一点的东西.

I guess a workaround is to store the output elsewhere as a string or something (it won't be too long), and append this manually with outfile.write(thestring) - but I was wondering if I am missing something within the module that facilitates this.

推荐答案

你当然可以将 subprocess.Popen 的输出附加到一个文件中,我每天都在使用它.这是我的做法:

You sure can append the output of subprocess.Popen to a file, and I make a daily use of it. Here's how I do it:

log = open('some file.txt', 'a')  # so that data written to it will be appended
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

(当然,这是一个虚拟的例子,我没有使用 subprocess 来列出文件...)

(of course, this is a dummy example, I'm not using subprocess to list files...)

顺便说一句,其他行为类似于文件的对象(特别是 write() 方法)可以替换此 log 项,因此您可以缓冲输出,并执行随心所欲(写入文件、显示等)[但这似乎并不容易,请参阅下面的评论].

By the way, other objects behaving like file (with write() method in particular) could replace this log item, so you can buffer the output, and do whatever you want with it (write to file, display, etc) [but this seems not so easy, see my comment below].

注意:可能具有误导性的是,subprocess 出于某种我不明白的原因,会在您想要编写的内容之前编写.所以,这是使用它的方法:

Note: what may be misleading, is the fact that subprocess, for some reason I don't understand, will write before what you want to write. So, here's the way to use this:

log = open('some file.txt', 'a')
log.write('some text, as header of the file
')
log.flush()  # <-- here's something not to forget!
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

所以提示是:不要忘记flush输出!

So the hint is: do not forget to flush the output!

这篇关于将 subprocess.Popen 输出附加到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)