Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何导入在另一个目录中的文件中编写的函数?_Python_Python 3.x - Fatal编程技术网

Python:如何导入在另一个目录中的文件中编写的函数?

Python:如何导入在另一个目录中的文件中编写的函数?,python,python-3.x,Python,Python 3.x,如果我有一个名为test的文件夹,其中有两个文件夹:functions和code。 在函数中,我有一个名为hello.py的文件,它有一个名为say_hello()的方法。 在代码中,我有一个名为main.py的文件,我想在其中使用say_hello() 结构如下: test/functions/hello.py test/code/main.py 我该怎么做呢?您应该以不同的方式处理项目结构。这是一个基本的例子,说明了如何做到这一点: test/ │ ├── test/ # your cod

如果我有一个名为test的文件夹,其中有两个文件夹:functions和code。 在函数中,我有一个名为
hello.py
的文件,它有一个名为
say_hello()
的方法。 在代码中,我有一个名为
main.py
的文件,我想在其中使用
say_hello()

结构如下:

test/functions/hello.py
test/code/main.py

我该怎么做呢?

您应该以不同的方式处理项目结构。这是一个基本的例子,说明了如何做到这一点:

test/
│
├── test/ # your code goes here
│   ├── __init__.py
│   ├── main.py
│   └── functions/
│       ├── __init__.py
│       ├── hello.py
│       └── byebye.py
|
|   # examples of what you can keep here:
├── LICENSE
└── README
然后在main.py中,您可以像这样导入和使用hello.py:

test/functions/hello.py
test/code/main.py
从函数导入hello
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#如果直接启动脚本,则上述条件为真
#(例如,双击其文件)
你好,说你好

您可以附加路径,然后导入

sys.path.append('/path/to/your/application/program/folder')

from test.functions import hello
from test.code import main
sys.path.append('/path/to/application/program/folder')
将是一种完美而简单的方法