Python Windows7:打开文件进行追加的奇怪行为
当我在 Windows 7 下使用 Python 以附加模式(“a+”)打开文件时,我看到奇怪的行为。
我想知道该行为实际上是否不正确,或者我误解了如何使用以下代码:
log_file= open(log_file_path, "a+")
return_code = subprocess.call(["make", target], stdout=log_file, stderr=subprocess.STDOUT)
log_file.close()
上述代码行未正确附加到文件。事实上,在后续运行中它甚至不会修改该文件。 我也使用 Python Shell 对其进行了测试。 第一次打开文件后,进行多个子进程调用将正确附加到文件,但是一旦文件被关闭并重新打开,它将永远不会再次附加。
有人有任何线索吗?
感谢
进一步简单地解决了这个问题,这是另一组将失败的步骤:
log_file=open("temp.txt", "a+")
log_file.write("THIS IS A TEST")
log_file.close()
log_file=open("temp.txt", "a+")
subprocess.call(["echo", "test"], stdout=log_file, stderr=subprocess.STDOUT, shell=True)
log_file.close()
如果您打开文件 temp.txt,我会看到以下内容:
测试
SA MUTHER F**测试
I am seeing odd behaviour when I open a file in append mode ('a+') under Windows 7 using Python.
I was wondering whether the behaviour is in fact incorrect or I am misunderstanding how to use the following code:
log_file= open(log_file_path, "a+")
return_code = subprocess.call(["make", target], stdout=log_file, stderr=subprocess.STDOUT)
log_file.close()
The above code lines does not properly append to the file. In fact on subsequent runs it won't even modify the file.
I tested it out using the Python Shell as well.
Once the file has been opened for the first time, making multiple subprocess calls will append properly to the file, however once the file has been closed and reopened it will never append again.
Anyone have any clues?
Thanks
To further simply the problem Here is another set of steps that will fail:
log_file=open("temp.txt", "a+")
log_file.write("THIS IS A TEST")
log_file.close()
log_file=open("temp.txt", "a+")
subprocess.call(["echo", "test"], stdout=log_file, stderr=subprocess.STDOUT, shell=True)
log_file.close()
If you open the file temp.txt here is what I see:
test
S A MUTHER F** TEST
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您的问题出在 shell=True 的使用上。来自 POpen 的 Python 文档:
所以看起来“echo”是命令,“test”作为参数发送到 shell,而不是“echo”。
因此,将子进程调用更改为:
或:
解决了问题,至少在我的测试中是这样。
It looks like your problem is in the use of shell=True. From Python documentation for POpen:
So it looks like "echo" is the command, and "test" gets sent as an argument to the shell, instead of to "echo".
So changing your subprocess call to either:
or:
Fixes the problem, at least in my testing.
请参阅http://mail.python.org/pipermail/python- list/2009-October/1221841.html
简要说明:以附加模式打开文件会使文件 ptr 处于依赖于实现的状态。力求最终在 Windows 上获得与 Linux 上相同的结果。
see http://mail.python.org/pipermail/python-list/2009-October/1221841.html
briefly: opening a file in append mode leaves the file ptr in an implementation-dependent state. seek to the end to get the same results on windows as on linux.