我正在编写一个使用 API 的程序。它需要坐标和一段时间,然后使用这些坐标将这段时间内的天气写入文件。有必要实现一个使用命令行的接口。这是使用它的模块的代码:
import click
from weather.table_creator.local_files.local_files import LocalFiles
@click.group()
def cli():
pass
@cli.command("stats")
@click.argument("lat")
@click.argument("lng")
@click.argument("start")
@click.argument("end")
def stats_cli(lat, lng, start, end):
ob1 = LocalFiles()
ob1.get_values(lat, lng, start, end)
ob1.transformation()
ob1.create_name()
ob1.record()
问题是当我通过终端运行模块时,出现以下错误:
(venv) D:\Documents\weather>python weather\cli\cli.py stats 56.85 60.61 2018-07-16 2018-07-18
Traceback (most recent call last):
File "weather\cli\cli.py", line 3, in <module>
from weather.table_creator.local_files.local_files import LocalFiles
ModuleNotFoundError: No module named 'weather'
而且,如果我只是执行文件,找到模块是没有问题的。在该程序的其他模块中,使用与此相同的行导入类,并且一切正常。
如您所见,这个未找到的模块存在并且感觉很好。来自另一个模块的类调用行由 PyCharm 自动编写。如何修复此错误?
Local_files 模块代码:
import copy
from weather.table_creator.api.api import API
class LocalFiles:
def __init__(self):
self.api = API()
def get_values(self, lat, lng, start, end):
response = self.api.send_request(lat, lng, start, end)
var = response.json()
hours = var['hours']
self.air_point = copy.deepcopy(hours)
self.hum_point = copy.deepcopy(hours)
self.time_point = copy.deepcopy(hours)
for i in range(0, len(hours)):
current_hour = hours[i]
air = current_hour['airTemperature']
hum = current_hour['humidity']
time = current_hour['time']
self.air_point[i] = air['noaa']
self.hum_point[i] = hum['noaa']
self.time_point[i] = time[:-9]
def transformation(self):
self.containing = 'дата/время;температура;влажность'
for i in range(0, len(self.air_point)):
self.containing = self.containing + f"\n{self.time_point[i]};{self.air_point[i]};{self.hum_point[i]}"
return self.containing
def create_name(self):
self.api.lat = str(self.api.lat)
self.api.lng = str(self.api.lng)
self.api.lat = self.api.lat.replace('.', '')
self.api.lng = self.api.lng.replace('.', '')
self.api.start = self.api.start.replace('-', '')
self.api.end = self.api.end.replace('-', '')
self.name_file = f'{self.api.lat} {self.api.lng} {self.api.start}-{self.api.end}'
return self.name_file
def record(self):
with open(f'{self.name_file}.csv', 'w') as f:
f.write(self.containing)
pass
return 'успех'
api模块代码:
import requests
from weather.table_creator.api.constants import BASE_URL, AUTHORISATION
class API:
def __init__(self, url=BASE_URL, aut=AUTHORISATION):
self.url = url
self.aut = aut
def send_request(self, lat, lng, start, end):
self.params = {
'params': ','.join(['humidity', 'airTemperature']),
'lat': lat,
'lng': lng,
'start': f'{start} 00:00',
'end': f'{end} 00:00'
}
self.lat = lat
self.lng = lng
self.start = start
self.end = end
self.response = requests.get(self.url, params=self.params, headers=self.aut)
# json_data = self.response.json()
return self.response
让它工作。例如,对于在导入之前
wether
尝试导入的所有模块中wether
whether
(原则上,将您运行的脚本添加到模块中就足够了,但谁知道您将如何以及从何处运行这些模块)
为了在 PyCharm 中正确启动,对于运行脚本的配置,将工作目录设置为
D:\\Documents\weather