There are many ways to import a Python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you, or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7
Example 1, Import a Python module with Python interpreter:
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say(): print("vixens cry")Get into the Python interpreter:
el@apollo:/home/el/foo$ python Python 2.7.3 (default, Sep 26 2013, 20:03:06) >>> import fox >>> fox.what_does_the_fox_say() vixens cryYou imported fox through the Python interpreter, invoked the Python function
what_does_the_fox_say()from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other Python file in place:
Put this in /home/el/foo2/mylib.py:
def moobar(): print("hi")Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py") moobar()run the file:
el@apollo:/home/el/foo$ python main.py hiThe function moobar was imported from mylib.py and made available in main.py
Example 3, Use from ... import ... functionality:
Put this in /home/el/foo3/chekov.py:
def question(): print("where are the nuclear wessels?")Put this in /home/el/foo3/main.py:
from chekov import question question()Run it like this:
el@apollo:/home/el/foo3$ python main.py where are the nuclear wessels?If you defined other functions in chekov.py, they would not be available unless you
import *
Example 4, Import riaa.py if it's in a different file location from where it is imported
Put this in /home/el/foo4/stuff/riaa.py:
def watchout(): print("computers are transforming into a noose and a yoke for humans")Put this in /home/el/foo4/main.py:
import sys import os sys.path.append(os.path.abspath("/home/el/foo4/stuff")) from riaa import * watchout()Run it:
el@apollo:/home/el/foo4$ python main.py computers are transforming into a noose and a yoke for humansThat imports everything in the foreign file from a different directory.
Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
Example 6, import your file via piggybacking the Python startuphook:
This example used to work for both Python 2 and Python 3, but now only works for Python 2. Python 3 got rid of this user startuphook feature set, because it was abused by low-skill Python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for Python 3, you'll have to get more creative. If I tell you how to do it, Python developers will disable that feature set as well, so you're on your own.
See: https://docs.python.org/2/library/user.html
Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
Run it, you should get this:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using Python 3, startuphooks are disabled there by default.
Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
Example 7, Most Robust: Import files in Python with the bare import command:
Make a new directory
/home/el/foo5/Make a new directory
/home/el/foo5/herpMake an empty file named
__init__.pyunder herp:el@apollo:/home/el/foo5/herp$ touch __init__.py el@apollo:/home/el/foo5/herp$ ls __init__.pyMake a new directory /home/el/foo5/herp/derp
Under derp, make another
__init__.pyfile:el@apollo:/home/el/foo5/herp/derp$ touch __init__.py el@apollo:/home/el/foo5/herp/derp$ ls __init__.pyUnder /home/el/foo5/herp/derp make a new file called
yolo.pyPut this in there:def skycake(): print("SkyCake evolves to stay just beyond the cognitive reach of " + "the bulk of men. SKYCAKE!!")The moment of truth, Make the new file
/home/el/foo5/main.py, put this in there;from herp.derp.yolo import skycake skycake()Run it:
el@apollo:/home/el/foo5$ python main.py SkyCake evolves to stay just beyond the cognitive reach of the bulk of men. SKYCAKE!!The empty
__init__.pyfile communicates to the Python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
Answer from Eric Leschinski on Stack OverflowThere are many ways to import a Python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you, or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7
Example 1, Import a Python module with Python interpreter:
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say(): print("vixens cry")Get into the Python interpreter:
el@apollo:/home/el/foo$ python Python 2.7.3 (default, Sep 26 2013, 20:03:06) >>> import fox >>> fox.what_does_the_fox_say() vixens cryYou imported fox through the Python interpreter, invoked the Python function
what_does_the_fox_say()from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other Python file in place:
Put this in /home/el/foo2/mylib.py:
def moobar(): print("hi")Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py") moobar()run the file:
el@apollo:/home/el/foo$ python main.py hiThe function moobar was imported from mylib.py and made available in main.py
Example 3, Use from ... import ... functionality:
Put this in /home/el/foo3/chekov.py:
def question(): print("where are the nuclear wessels?")Put this in /home/el/foo3/main.py:
from chekov import question question()Run it like this:
el@apollo:/home/el/foo3$ python main.py where are the nuclear wessels?If you defined other functions in chekov.py, they would not be available unless you
import *
Example 4, Import riaa.py if it's in a different file location from where it is imported
Put this in /home/el/foo4/stuff/riaa.py:
def watchout(): print("computers are transforming into a noose and a yoke for humans")Put this in /home/el/foo4/main.py:
import sys import os sys.path.append(os.path.abspath("/home/el/foo4/stuff")) from riaa import * watchout()Run it:
el@apollo:/home/el/foo4$ python main.py computers are transforming into a noose and a yoke for humansThat imports everything in the foreign file from a different directory.
Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
Example 6, import your file via piggybacking the Python startuphook:
This example used to work for both Python 2 and Python 3, but now only works for Python 2. Python 3 got rid of this user startuphook feature set, because it was abused by low-skill Python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for Python 3, you'll have to get more creative. If I tell you how to do it, Python developers will disable that feature set as well, so you're on your own.
See: https://docs.python.org/2/library/user.html
Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
Run it, you should get this:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using Python 3, startuphooks are disabled there by default.
Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
Example 7, Most Robust: Import files in Python with the bare import command:
Make a new directory
/home/el/foo5/Make a new directory
/home/el/foo5/herpMake an empty file named
__init__.pyunder herp:el@apollo:/home/el/foo5/herp$ touch __init__.py el@apollo:/home/el/foo5/herp$ ls __init__.pyMake a new directory /home/el/foo5/herp/derp
Under derp, make another
__init__.pyfile:el@apollo:/home/el/foo5/herp/derp$ touch __init__.py el@apollo:/home/el/foo5/herp/derp$ ls __init__.pyUnder /home/el/foo5/herp/derp make a new file called
yolo.pyPut this in there:def skycake(): print("SkyCake evolves to stay just beyond the cognitive reach of " + "the bulk of men. SKYCAKE!!")The moment of truth, Make the new file
/home/el/foo5/main.py, put this in there;from herp.derp.yolo import skycake skycake()Run it:
el@apollo:/home/el/foo5$ python main.py SkyCake evolves to stay just beyond the cognitive reach of the bulk of men. SKYCAKE!!The empty
__init__.pyfile communicates to the Python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
In python 2.x:
- Just
import filewithout the .py extension - A folder can be marked as a package, by adding an empty
__init__.pyfile - 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))
Type help(__import__) for more details.
Importing a python file into another python file
Import files directly from file location - Ideas - Discussions on Python.org
How to import variable from parent __init__.py package?
Tab delineated python 3 .txt file reading
Hiya, so I've just recently started learning python by completing some challenges and one of them is to import the functions made in one python file to another so they can be tested. I'm trying to import this file but it keeps telling me there's no module by the name I'm putting in. I can't see any spelling mistakes in the file name and I believe I'm using the correct syntax and function so I don't know what the issue is. These are the things I've tried and the error message I keep getting.
(File I'm trying to import is called UnitTests.py)
attempt #1
import UnitTests
attempt #2
from UnitTests import *
attempt #3
import sys
sys.path.append(
'coding/python/boot.dev/Ch. 5: Testing + Debugging')
from UnitTests import * Error message
Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'UnitTests'
SEMI-RESOLVED?
After adding the specific function I wanted it to run the script can now use the function (called total_xp)
from UnitTests import total_xp
The code as a whole is working now and that's the important part but the semi-unresolved bit for me is if I run just the line from UnitTests import total_xp it once again says the file UnitTests doesn't exist and I was wondering why that is? My friend said it may be because running the whole script it knows which directory itself is in but just running the single line is just running the command and therefore it doesn't know where to find it, but this also doesn't make sense to me because on my third attempt I told it where the directory was and it still didn't work. Again it's not super important because you'd never import the file to another script if you're not going to use a function from said file, it's more out of curiosity now that I want to know why I can't just run it as a single line.