我必须将子流程的输出转储到以附加模式打开的文件中

from subprocess import Popen

fh1 = open("abc.txt", "a+") # this should have worked as per my understanding

# fh1.readlines() # Adding this solves the problem

p = Popen(["dir", "/b"], stdout = fh1, shell=True)

print p.communicate()[0]
fh1.close()

上面的代码覆盖了我不想要的文件abc.txt,取消注释fh1.readlines()会将光标移动到适当的位置,这是一个临时解决方案

有什么基本的我想念的吗?
In [18]: fh1 = open("abc.txt",'a')

In [19]: fh1.tell() # This should be at the end of the file
Out[19]: 0L

In [20]: fh1 = open("abc.txt",'r')

In [21]: print fh1.readlines()
['1\n', '2\n', '3\n', '4\n', '5\n']

最佳答案

将光标放在文件末尾而不读取文件的简单方法是:

fh1.seek(2)
# .seek(offset, [whence]) >> if offset = 2 it will put the cursor in the given position relatively
# to the end of the file. default 'whence' position is 0, so at the very end

关于python - 在追加模式下将子流程输出转储到文件中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14332141/

10-14 23:55