ava*_*sal 6 python file-io subprocess
我必须将子进程的输出转储到以附加模式打开的文件中
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()
Run Code Online (Sandbox Code Playgroud)
但是上面的代码会覆盖我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']
Run Code Online (Sandbox Code Playgroud)
在我的 OS X 中,python 2.7 和 3.3 都可以正常工作。
\n\nadylab:Downloads adyliu$ cat ./a.txt\na\nb\nc\nd\ne\nf\nadylab:Downloads adyliu$ python -V\nPython 2.7.2\nadylab:Downloads adyliu$ python3 -V\nPython 3.3.0\nadylab:Downloads adyliu$ python -c "print(open(\'./a.txt\',\'a\').tell())"\n12\nadylab:Downloads adyliu$ python3 -c "print(open(\'./a.txt\',\'a\').tell())"\n12\nRun Code Online (Sandbox Code Playgroud)\n\n在 python 文档中:
\n\n\n\n\nstdin、stdout 和 stderr 分别指定执行的程序\xe2\x80\x99 标准输入、标准输出和标准错误文件句柄。\n 有效值为 PIPE、DEVNULL、现有文件描述符(正整数) 、现有文件对象和 None。PIPE 指示\n 应创建到子级的新管道。DEVNULL 表示将使用特殊文件 os.devnull。使用默认设置\n None,不会发生重定向;子\xe2\x80\x99s 文件句柄将从父\n 继承。此外,stderr 可以是 STDOUT,这表明来自应用程序的 stderr 数据应该被捕获到与 stdout 相同的文件句柄中。
\n
因此“Popen”进程不会重置文件对象的当前流位置。
\n