如何导入其他 Python 文件? [英] How to import other Python files?

查看:45
本文介绍了如何导入其他 Python 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中导入其他文件?

How do I import other files in Python?

  1. 我究竟如何导入像 import file.py 这样的特定 python 文件?
  2. 如何导入文件夹而不是特定文件?
  3. 我想在运行时根据用户动态加载 Python 文件输入.
  4. 我想知道如何从文件中只加载一个特定的部分.
  1. How exactly can I import a specific python file like import file.py?
  2. How can I import a folder instead of a specific file?
  3. I want to load a Python file dynamically at runtime, based on user input.
  4. I want to know how to load just one specific part from the file.

例如,在 main.py 我有:

from extra import * 

虽然这给了我 extra.py 中的所有定义,但也许我想要的只是一个定义:

Although this gives me all the definitions in extra.py, when maybe all I want is a single definition:

def gap():
    print
    print

为了从 extra.py 获取 gap,我在 import 语句中添加了什么?

What do I add to the import statement to just get gap from extra.py?

推荐答案

importlib 已添加到 Python 3 以编程方式导入模块.

importlib was added to Python 3 to programmatically import a module.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

应该从 moduleName 中删除 .py 扩展名.该函数还为相对导入定义了一个 package 参数.

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

在 python 2.x 中:

In python 2.x:

  • 只需导入文件,不带 .py 扩展名
  • 可以通过添加一个空的__init__.py 文件将文件夹标记为包
  • 您可以使用 __import__ 函数,它将模块名称(不带扩展名)作为字符串扩展名
  • Just import file without the .py extension
  • A folder can be marked as a package, by adding an empty __init__.py file
  • You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

输入 help(__import__) 了解更多详情.

Type help(__import__) for more details.

这篇关于如何导入其他 Python 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆