请求.urlretrieve在pythonywh中作为计划任务运行时失败

2024-10-01 02:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.py脚本,当我在控制台中运行它时,它可以工作,但是当我将它作为自动任务进行调度时,它似乎失败了。脚本使用urllib.request请求(我确保将Hashbang设置为运行支持该包的python3.6)点击并从特定URL下载文件。。同样,当我手动运行它时没有问题,但是当它作为计划任务运行时,我得到以下错误:

Traceback (most recent call last):   File
"/home/laiAdmin/Scripts/FullAutoSubStats.py", line 32, in <module>
     urllib.request.urlretrieve(URL, dlFileName)   File "/usr/lib/python3.6/urllib/request.py", line 258, in urlretrieve
     tfp = open(filename, 'wb') FileNotFoundError: [Errno 2] No such file or directory:
 '/home/laiAdmin/Data_Files/Downloads/FWdirect-Daily-Stats-Parser-autoDl-2018-05-08.json'

 2018-05-08 16:48:11 -- Completed task, took 6.00 seconds, return code
 was 1.

它指向的代码段如下(出于安全目的,隐藏完整的URL):

#Get timestamp and PWD
cwd = os.getcwd()
now = DT.datetime.utcnow()-DT.timedelta(hours=6)
todayStr = DT.datetime.strftime(now,"%Y-%m-%d")
nowStr = DT.datetime.strftime(now,"%m/%d/%Y %H:%M:%S")

#Request to download a new json file:
rootdir = cwd+'/Data_Files/Downloads/'
URL = "https://files.mailparser.io/d/*****" 
#(hiding the full URL here for security purposes)
fn = "FWdirect-Daily-Stats-Parser-autoDl-"+todayStr+".json"
dlFileName = rootdir+fn
urllib.request.urlretrieve(URL, dlFileName)

最后一行是回溯发生的地方。请帮助我理解为什么当我在控制台中点击run时,它会运行,但当我将它安排为任务时,它会失败。你知道吗


Tags: py脚本jsonurlhomedatetimerequestline
1条回答
网友
1楼 · 发布于 2024-10-01 02:32:27

很傻,但我刚想出来。结果是,当计划任务运行时,它会从导致问题的其他目录运行。你知道吗

多亏了Python街的贾尔斯给我的消息:https://www.pythonanywhere.com/forums/topic/12790/#id_post_49647

需要cd到任务计划程序中的正确目录:

cd /home/laiAdmin/something/something; python3.6 /home/laiAdmin/myscript.py

相关问题 更多 >