python-3.x pyrun -相对导入失败

agxfikkp  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(150)

我有以下文件夹组织。

pyrun-pb
├── folder-1
│   ├── common.py
│   ├── data.py
│   └── test-run-1.py
└── test-run-2.py

文件test-run-1.py使用runpy.run_path成功,与test-run-2.py相反。这是一个终端会话。我遗漏了什么?

> python /path/to/pyrun-pb/folder-1/test-run-1.py
{'test': 'example'}
> python /path/to/pyrun-pb/test-run-2.py
Traceback (most recent call last):
  File "/path/to/pyrun-pb/test-run-2.py", line 8, in <module>
    data = run_path((THIS_DIR / 'folder-1') / 'data.py')
  File "//path/to/python3.9/runpy.py", line 288, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "//path/to/python3.9/runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "//path/to/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/path/to/pyrun-pb/folder-1/data.py", line 3, in <module>
    from common import CVAR
ModuleNotFoundError: No module named 'common'

代码

一个一个二个一个一个一个三个一个一个一个一个一个一个四个一个一个一个一个一个五个一个

cwdobuhd

cwdobuhd1#

这是一个“肮脏”的工作解决方案。

#!/usr/bin/env python3

from pathlib import Path

import os
import sys
from runpy import run_path

THIS_DIR = Path(__file__).parent

FILE_CALLED = (THIS_DIR / 'folder-1') / 'data.py'

dirpath = os.fspath(str(FILE_CALLED.parent))
sys.path.insert(0, dirpath)

data = run_path((THIS_DIR / 'folder-1') / 'data.py')

sys.path.remove(dirpath)

print(data["XTRA"])

相关问题