简体   繁体   English

如何从另一个 python 脚本导入帮助文件 (.py)?

[英]How do I import helper files (.py) from another python script?

I am brand new to working with python so this question might be basic.我是使用 python 的新手,所以这个问题可能很基础。 I am attempting to import five helper files into a primary script, the directory setup is as follows and both the script I'm calling from and the helper scripts are located within src here in this path-我正在尝试将五个帮助程序文件导入到主脚本中,目录设置如下,我调用的脚本和帮助程序脚本都位于此路径中的 src 中 -

/Users/myusername/Desktop/abd-datatable/src

I am currently importing as-我目前正在进口-

import helper1 as fdh
import helper2 as hdh
..
import helper5 as constants

The error I see is我看到的错误是

  File "/Users/myusername/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/22.77756/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)

ModuleNotFoundError: No module named 'src'

I have also attempted the following for which the import was still unsuccessful:我还尝试了以下导入仍然不成功的操作:

import src.helper1 as fdh
..
import src.helper5 as constants

and

from src import src.helper1 as fdh
...
from src import helper5 as constants

and tried adding the following to the head of the script-并尝试将以下内容添加到脚本的头部 -

import sys
import os

module_path = os.path.abspath(os.getcwd())

if module_path not in sys.path:
    sys.path.append(module_path)

Would be very grateful for any pointers on how to debug this!非常感谢有关如何调试它的任何指示!

Seems likely that it's a path issue.似乎这是一个路径问题。

In your case, if you want to import from src , you would need to add Users/myusername/Desktop/abd-datatable to the path.在您的情况下,如果您想从src导入,则需要将Users/myusername/Desktop/abd-datatable添加到路径中。

os.getcwd() is getting the path you invoke the script from, so it would only work if you are invoking the script from Users/myusername/Desktop/abd-datatable . os.getcwd()正在获取您从中调用脚本的路径,因此它仅在您从Users/myusername/Desktop/abd-datatable调用脚本时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM