简体   繁体   English

通过在 Python 中导入文件来防止代码重复

[英]Prevent code duplication by importing files in Python

When using PHP, I write code in a separate file that I include using require_once() or include_once() .使用 PHP 时,我在一个单独的文件中编写代码,我使用require_once()include_once()将其包含在内。 Is there something similar in Python as well? Python 中是否也有类似的东西?

I read this answer: Is there an alternative python function does as PHP include() function?我读了这个答案: Is there an alternative python function does as PHP include() ZC1C425268E68385F1A45A?

The file I want to run in run.py .我想在run.py中运行的文件。 The file I want to include is funcs.py .我要包含的文件是funcs.py The funcs.py file is located inside a folder called includes . funcs.py文件位于名为includes的文件夹中。 The folder includes and run.py are in the same location.文件夹includesrun.py位于同一位置。

I created an empty file __init__.py .我创建了一个空文件__init__.py I use from includes import funcs .我使用from includes import funcs However, I get the error No Module named includes .但是,我收到错误No Module named includes

What am I doing wrong?我究竟做错了什么?

In this case you don't need __init__.py if you're using Python 3 .在这种情况下,如果您使用的是Python 3 ,则不需要__init__.py The following structure should work:以下结构应该有效:

run.py
includes/
    funcs.py

If you're running this script from the folder with your run.py then the following should work:如果您从带有run.py的文件夹中运行此脚本,那么以下内容应该可以工作:

from includes import funcs

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

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