#python #python-import
#питон #python-импорт
Вопрос:
У меня есть скрипт на Python, который я использую для запуска некоторых симуляций. Эти симуляции определены в другом скрипте Python (preprocess.py и симуляция.py) и поскольку они управляются репозиторием git, я копирую их в другое место перед их запуском, чтобы избежать генерации всех выходных данных в репозитории.
Для этого у меня есть что-то вроде этого
vncs.py
import os
import sys
import shutil
import distutils.dir_util
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", help="Directory where the results will be saved", dest="output")
parser.add_argument("-i", "--input", help="Directory containing the scene", dest="input")
parser.add_argument("-p", "--preprocess", help="Specifies if the preprocess must be executed", dest="preprocess", action="store_true")
parser.add_argument("-s", "--simulate", help="Specifies if the simulation must be executed", dest="simulate", action="store_true")
args = parser.parse_args()
# Copy the scene
in_dir = args.input
index = in_dir.rfind("/")
out_dir = args.output in_dir[index 1:]
print(in_dir)
print(out_dir)
shutil.copytree(in_dir, out_dir, dirs_exist_ok=True)
current_dir = os.getcwd()
os.chdir(out_dir)
sys.path.append(out_dir)
from . import preprocess
from . import simulation
if args.preprocess:
preprocess.run()
if args.simulate:
simulation.run()
os.chdir(current_dir)
Я в основном копирую входной каталог в выходной каталог и пытаюсь импортировать preprocess.py и симуляция.файлы py, но он завершается сбоем со следующей ошибкой
python vncs.py -i ./EnforcedBeam -o ../../
./EnforcedBeam
../../EnforcedBeam
Traceback (most recent call last):
File "/home/jjcasmar/projects/VNCS/Scenes/vncs.py", line 32, in <module>
from . import preprocess
ImportError: attempted relative import with no known parent package
Что в этом плохого?
Комментарии:
1. Что, если вы просто сделаете
import simulation
? Кроме того, рассмотрите возможность использования importlib для динамического импорта2. Я попытался добавить выходной каталог в sys.path,
import simulation
но, по-видимому, он не может найти файл. Я не могу протестировать importlib