简体   繁体   English

停止在Windows命令提示符下运行的python脚本时避免数据丢失

[英]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.

相关问题 在Windows命令提示中运行Python脚本时如何修复NameError - How to fix NameError when running Python Script in Windows Command Prompt Python:从python脚本的Windows命令提示符中执行windows命令 - Python: Executing the windows command in windows command prompt from python script 从命令行运行 python 脚本时,PythonWin 也会运行。 我怎样才能避免这种情况? - When running a python script from command line, PythonWin also runs. How can I avoid this? Python在Powershell中运行,但没有命令提示符 - Python runs in Powershell but not command prompt 如何在Windows命令行中使运行python的命令成为脚本? - How to make a command that runs python a script in Windows command line? 使用Windows命令提示符查找python脚本的Windows PID - Find Windows PID of a python script with Windows Command Prompt 重新启动脚本后命令提示符(Windows)和 python 脚本出现问题 - Issue with command prompt (windows) and python script after restarting script Python - 如何在脚本运行时隐藏 Windows 命令提示符屏幕? - Python - how can i hide the windows command prompt screen when the script is running? 我的脚本在外壳程序上运行,但不在命令提示符下运行 - My script runs on the shell but not on the command prompt 如何在命令提示符Windows 10中运行python脚本 - How to run python script in Command Prompt Windows 10
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM