python - 进程被杀死/完成后出现将 python print() 的输出写入文件
问题描述
我的代码中有几个 print() 语句。我想在一夜之间运行代码并让它们写入文件。我尝试将输出重定向到文件:
python mycode.py >> log.txt
在 python 进程运行时,我看不到任何写入文件的内容。当我终止进程并打开日志文件时,我在其中找到了输出。
当我在每个打印语句中明确指定文件句柄时,也出现了类似的行为:
output_file = open('log.txt','w')
print('blablabla', file=output_file)
我怎样才能print
立即写入文件?我错过了什么吗?
解决方案
你能试试这个并告诉我它是否立即更新。我总是在PyCharm中使用这种语法。我希望它也适用于你。
如果你想一次插入一堆数据。
with open("log.txt", 'w') as test:
print ("hello world!", file=test)
如果要向 中插入数据.txt
,请执行一些处理,然后再次返回以将更多数据添加到.txt
test = open("log.txt", 'w')
print ("hello world!", file=test)
#==== Do some processes ====
print("This's the end of the file")
test.close()
推荐阅读
- pine-script - Pinescript 动态警报消息更改 tostring 变量中策略权益的值
- c# - ANTLR 4 未能识别 '..' 标记以支持两个 '.'
- jasperserver - 在 JasperReports Server 7.8.0 CE 中创建域
- php - 无法使用 PHP 解析具有多个命名空间的 XML
- php - fwrite 后是否需要 fflush()?
- php - mysqldump 从命令行工作,但从 php exec 拒绝访问
- javascript - Docker 中的 Angular 构建失败 [ERR_STREAM_DESTROYED]:流被销毁后无法调用 write
- ssl - 为什么我会收到仍然有效的证书的 SSL 已过期错误?
- deployment - 控制 Wildfly 取消部署
- javascript - 如何在输入标签中捕获条形码十六进制代码击键