[英]`with open…` doesn't work in scheduled task on Windows
I work with Python on Linux, but I'm forced to schedule a task on Windows. 我在Linux上使用Python,但是我不得不在Windows上安排任务。 I was having a hard time automating my scripts here.
我在这里很难自动化我的脚本。 The best alternative for cron I have found is this command
我发现的cron最好的替代方法是此命令
schtasks /Create /SC MINUTE /TN TestTask_Python /TR "C:\\Program Files (x86)\\Python36-32\\python.exe C:\\Users\\user_name\\Desktop\\test.py"
It runs the script every minute and it kind of works. 它每分钟运行一次脚本,并且可以正常工作。 Documentation.
文档。
Case 1. Running from IDE. 情况1.从IDE运行。 (PyCharm/Idle) Script works.
(PyCharm / Idle)脚本有效。
Case 2. Running from cmd. 情况2。从cmd运行。
> python test.py
Script works. > python test.py
脚本有效。
Case 3. Runs scheduled task. 情况3。运行计划的任务。 The script works partially.
该脚本部分起作用。
Case3 prints not added
and it's done, while Case1 and Case2 prints not added
, adds datetime
to test_time.txt
and prints added
. Case3的打印
not added
并完成,而Case1和Case2的打印not added
, test_time.txt
datetime
添加到test_time.txt
并added
了test_time.txt
。
import time
import datetime
import json
from datetime import date
if __name__ == "__main__":
now = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
print('not added')
time.sleep(2)
with open('test_time.txt', 'a+') as pf:
pf.write('{0} \n'.format(now))
print('added')
time.sleep(1)
time.sleep(1)
I double checked my enviro variables and python PATH matches the path I put in the schtasks cmd. 我仔细检查了我的环境变量,并且python PATH与我在schtasks cmd中输入的路径匹配。
Am I missing something? 我想念什么吗? Why
with open...
doesn't work in this case? 为什么
with open...
在这种情况下不起作用?
The process has a different working directory when run as a windows task. 作为Windows任务运行时,该进程具有不同的工作目录。
Use an absolute path in your call to open()
. 在对
open()
调用中使用绝对路径 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.