How to import other Python files?

2018-12-31 06:16发布

How do I import other files in Python?

  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.

For example, in main.py I have:

from extra import * 

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

def gap():
    print
    print

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

14条回答
人气声优
2楼-- · 2018-12-31 06:45

You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type

from root.parent.folder.file import variable, class, whatever

查看更多
十年一品温如言
3楼-- · 2018-12-31 06:48

To import a specific Python file at 'runtime' with a known name:

import os
import sys

...

scriptpath = "../Test/MyModule.py"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule
查看更多
与君花间醉酒
4楼-- · 2018-12-31 06:48

In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:

Directory Structure:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

In app.py, append path of client to sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

Run

user@host:/path/to/common_dir$ python3 application/app.py

This solution works for me in cli, as well as PyCharm.

查看更多
无与为乐者.
5楼-- · 2018-12-31 06:53

Just to import python file in another python file

lets say I have helper.py python file which has a display function like,

def display():
    print("I'm working sundar gsv")

Now in app.py, you can use the display function,

import helper
helper.display()

The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 06:58

This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.

查看更多
牵手、夕阳
7楼-- · 2018-12-31 06:59

importlib is recent addition in Python to programmatically import a module. It just a wrapper around __import__ See https://docs.python.org/3/library/importlib.html#module-importlib

import importlib

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

Update: Answer below is outdated. Use the more recent alternative above.

  1. Just import file without the '.py' extension.

  2. You can mark a folder as a package, by adding an empty file named __init__.py.

  3. You can use the __import__ function. It takes the module name as a string. (Again: module name without the '.py' extension.)

    pmName = input('Enter module name:')
    pm = __import__(pmName)
    print(dir(pm))
    

    Type help(__import__) for more details.

查看更多
登录 后发表回答