

Put this code into your main.py (can be anywhere): import user

Return "cookie and sky pie people can't go up and "

Secretmessage = classmethod( secretmessage ) Put this code into your home directory in ~/.pythonrc.py class secretclass: That imports everything in the foreign file from a different directory.Įxample 5, use os.system("python yourfile.py") import osĮxample 6, import your file via piggybacking the python startuphook: Run it: :/home/el/foo4$ python main.pyĬomputers are transforming into a noose and a yoke for humans Put this in /home/el/foo4/main.py: import sys Print "computers are transforming into a noose and a yoke for humans" Put this in /home/el/foo4/stuff/riaa.py: def watchout(): If you defined other functions in chekov.py, they would not be available unless you import *Įxample 4, Import riaa.py if it’s in a different file location from where it is imported Run it like this: :/home/el/foo3$ python main.py Put this in /home/el/foo3/main.py: from chekov import question Put this in /home/el/foo3/chekov.py: def question(): The function moobar was imported from mylib.py and made available in main.pyĮxample 3, Use from … import … functionality: Run the file: :/home/el/foo$ python main.py Put this in /home/el/foo2/main.py: execfile("/home/el/foo2/mylib.py") Put this in /home/el/foo2/mylib.py: def moobar(): You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.Įxample 2, Use execfile or ( exec in Python 3) in a script to execute the other python file in place: Get into the python interpreter: :/home/el/foo$ python Put this in /home/el/foo/fox.py: def what_does_the_fox_say(): I’ll start out explaining the easiest example #1, then I’ll move toward the most professional and robust example #7Įxample 1, Import a python module with python interpreter:

There are many ways to import a python file, all with their pros and cons.ĭon’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.
