我有一个Python脚本,可以进行一些网络爬虫,然后打开并将解析的数据转储到同一目录中的JSON文件中。通过任务调度程序运行的批处理文件运行脚本时,通过CLI手动运行脚本,但数据未写入JSON文件,一切正常。
通过批处理文件运行时,我设法证明所有数据都存在于Python脚本中。某种程度上,处理JSON文件的功能中只有一部分没有运行。
Python脚本:
# Packages used:
import requests
from bs4 import BeautifulSoup
import smtplib
import time
from win10toast import ToastNotifier
import json
# Web Scraping...
my_json = {}
def function1():
# Web scraping for data...
json_function(data)
# Below is the function that is not functioning
def json_function(data):
my_json[time.strftime("%Y-%m-%d %H:%M")] = f"{data}"
with open ('json_file.json') as my_dict:
info = json.load(my_dict)
info.update(my_json)
with open('json_file.json','w') as my_dict:
json.dump(info,my_dict)
# A few other functions that work regardless...
# Call function
function1()
批处理文件:
"C:\Users\...pythonw.exe" "C:\Users...script.pyw"
JSON文件:
{"Key":"Value"}
每个文件都在同一目录中。
从CLI运行时,会发生预期的结果-键值会附加到JSON文件中。自动运行时(通过批处理和任务计划程序运行),没有可见的错误,并且所有脚本(保存为json_function)均按预期运行。
答案 0 :(得分:0)
谢谢@PRMoureu的回答,感谢@Mofi的详细解释。
答案是确保所有引用的文件都引用了完整路径:
def json_function(data):
my_json[time.strftime("%Y-%m-%d %H:%M")] = f"{data}"
with open ('C:/.../json_file.json') as my_dict:
info = json.load(my_dict)
info.update(my_json)
with open('C:/.../json_file.json','w') as my_dict:
json.dump(info,my_dict)
或者,将“任务计划程序”定向到工作目录,以避免在默认的根目录中运行批处理。