Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing files in Python?

How do I import Python files during execution?

I have created 3 file a.py,b.py and c.py in a path C:\Users\qksr\Desktop\Samples

The files contain the code as shown below:

a.py

from c import MyGlobals

def func2():
    print MyGlobals.x
    MyGlobals.x = 2

b.py

import a
from c import MyGlobals

def func1():
    MyGlobals.x = 1      

if __name__ == "__main__":
    print MyGlobals.x
    func1()
    print MyGlobals.x
    a.func2()
    print MyGlobals.x

c.py

class MyGlobals(object):
    x = 0

When I execute the code b.py the following error is thrown:

ImportError: No module named a

I believe my working directory is default and all the file a,b,c is just created by me in the samples folder.

How do I import python files in Python?

like image 448
Kaushik Avatar asked Mar 28 '13 12:03

Kaushik


2 Answers

If you are working in the same directory, that is, b.py is in the same folder as a.py, I am unable to reproduce this problem (and do not know why this problem occurs), but it would be helpful if you post what os.getcwd() returns for b.py.

If that's not the case, add this on top of b.py

import sys
sys.path.append('PATH TO a.py')

OR if they are in the same path,

import sys
sys.path.append(os.basename(sys.argv[0])) # It should be there anyway but still..
like image 75
pradyunsg Avatar answered Oct 26 '22 23:10

pradyunsg


There are many ways to import a python file:

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 start out explaining the the easiest console example #1, then move toward the most professional and robust program example #5

Example 1, Import a python module with python interpreter:

  1. Put this in /home/el/foo/fox.py:

    def what_does_the_fox_say():
      print "vixens cry"
    
  2. 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 cry
    >>> 
    

    You invoked the python function what_does_the_fox_say() from within the file fox through the python interpreter.

Option 2, Use execfile in a script to execute the other python file in place:

  1. Put this in /home/el/foo2/mylib.py:

    def moobar():
      print "hi"
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    The function moobar was imported from mylib.py and made available in main.py

Option 3, Use from ... import ... functionality:

  1. Put this in /home/el/foo3/chekov.py:

    def question():
      print "where are the nuclear wessels?"
    
  2. Put this in /home/el/foo3/main.py:

    from chekov import question
    question()
    
  3. 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 *

Option 4, Import riaa.py if it's in a different file location from where it is imported

  1. Put this in /home/el/foo4/bittorrent/riaa.py:

    def watchout_for_riaa_mpaa():
      print "there are honeypot kesha songs on bittorrent that log IP " +
      "addresses of seeders and leechers. Then comcast records strikes against " +
      "that user and thus, the free internet was transmogified into " +
      "a pay-per-view cable-tv enslavement device back in the 20th century."
    
  2. Put this in /home/el/foo4/main.py:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/bittorrent"))
    from riaa import *
    
    watchout_for_riaa_mpaa()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py 
    there are honeypot kesha songs on bittorrent...
    

    That imports everything in the foreign file from a different directory.

Option 5, Import files in python with the bare import command:

  1. Make a new directory /home/el/foo5/
  2. Make a new directory /home/el/foo5/herp
  3. Make an empty file named __init__.py under herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.py file:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
    
  7. The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

    from herp.derp.yolo import skycake
    skycake()
    
  8. 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__.py file 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

Bonus protip, whether you are using Mac, Linux or Windows, you need to be using python's idle editor as described here. It will unlock your python world. http://www.youtube.com/watch?v=DkW5CSZ_VII

like image 22
Eric Leschinski Avatar answered Oct 26 '22 22:10

Eric Leschinski