[英]avoid data loss when stopping python script that runs in windows command prompt
I've written a Python-script, that scrapes certain websites. 我写了一个Python脚本,刮了某些网站。 I run it from windows command line and use the command line to direct the "print()"-output of the script into a txt-file. 我从Windows命令行运行它,并使用命令行将脚本的“ print()”输出定向到txt文件中。
Like this: 像这样:
MyScraper.py > outputOfMyScraper.txt. MyScraper.py> outputOfMyScraper.txt。
Now and then I have to kill/stop the script before the run is complete (I close the windows command line). 在运行完成之前,我必须不时地杀死/停止脚本(我关闭Windows命令行)。 9 of 10 times this has no impact on the outputOfMyScraper.txt-file, but now and then the content of the file will be deleted when closing the command line. 10次中的9次对outputOfMyScraper.txt文件没有影响,但是在关闭命令行时,该文件的内容将不时地被删除。
Is there - besides changing the code in the scraper to write content directly to a csv-file and avoid the windows command line totally - a way of stopping the script without the risk of losing data? 除了更改刮板中的代码以直接将内容写入csv文件并完全避免Windows命令行之外,还有没有一种方法可以停止脚本而不会丢失数据呢?
Thank you very much. 非常感谢你。
You can force Python to switch standard output to unbuffered mode by adding -u
switch: 您可以通过添加-u
switch来强制Python将标准输出切换为非缓冲模式:
python -u MyScraper.py > outputOfMyScraper.txt
Another way is to set the PYTHONUNBUFFERED
environment variable to non-empty string: 另一种方法是将PYTHONUNBUFFERED
环境变量设置为非空字符串:
set PYTHONUNBUFFERED=1
MyScraper.py > outputOfMyScraper.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.