6

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Kaushik
  • 1,264
  • 8
  • 20
  • 32
  • if all files are of same path then its ok – sharafjaffri Mar 28 '13 at 12:09
  • could you print `sys.path` before the ImportError happens? – User Mar 28 '13 at 12:19
  • When i print sys.path i get : ['C:\\Users\\qksr\\Desktop\\Samples', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\win32', 'C:\\Python27\\lib\\site-packages\\win32\\lib', 'C:\\Python27\\lib\\site-packages\\Pythonwin', 'C:\\Users\\qksr\\Desktop'] – Kaushik Mar 28 '13 at 12:37
  • @User we can see that the path is being appended and yet i still face That particular problem. – Kaushik Mar 28 '13 at 12:39
  • What happens if you open a command window, `cd` to that directory, launch `python.exe` and type `import a` in the prompt? – Janne Karila Mar 28 '13 at 13:03

6 Answers6

7

Tweaking PYTHONPATH is generally not a very good idea.

A better way is to make your current directory behave like a module, by adding a file named __init__.py, which can be empty.

Then the python interpretter allows you to import files from that directory.

pradyunsg
  • 18,287
  • 11
  • 43
  • 96
Benoit
  • 163
  • 7
6

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..
pradyunsg
  • 18,287
  • 11
  • 43
  • 96
  • @Schoolboy C:\Users\qksr\Desktop\Samples this what i get when i do os.getcwd() – Kaushik Mar 28 '13 at 12:31
  • As I said, I am unable to reproduce this problem on my system (windows 7). I did the same (created a folder `Samples` on Desktop, and put the 3 files there), but nothing came up.(except for 0 1 1 2) :) Try the solution I suggested. Also, When using Python use modules when needed (unless you have a good reason not to). – pradyunsg Mar 28 '13 at 12:35
6

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

Community
  • 1
  • 1
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
1

Referring to: I would like to know how to import a file which is created in any path outside the default path ?

import sys

sys.path.append(directory_path) # a.py should be located here
User
  • 14,131
  • 2
  • 40
  • 59
  • If all files are on same folders then no need for any path addition it should work fine. – sharafjaffri Mar 28 '13 at 12:12
  • @ User: Do you mean to say in b.py i need to add import sys and sys.path.append('C:\Users\qksr\Desktop\Samples'). Where the files a.py , b.py,c.py are located in that path. – Kaushik Mar 28 '13 at 12:13
  • try it out. Sadly I can not refer to the error you get but only to the question you asked. I do not know, why you get the error. – User Mar 28 '13 at 12:14
  • @sharafjaffri All the files are in the same folder. The folder is located in the desktop. – Kaushik Mar 28 '13 at 12:15
  • @User i tried the same thing you said and yet it throws the same error . – Kaushik Mar 28 '13 at 12:15
  • @karthik am using Linux mint and created all three files, python b.py is working fine. – sharafjaffri Mar 28 '13 at 12:17
  • @karthik for Windows it could be a problem. you can add this line at the top of your b.py sys.path.append(os.path.dirname(\_\_file\_\_)) – sharafjaffri Mar 28 '13 at 12:18
0

By default, Python won't import modules from the current working directory. There's 2 (maybe more) solutions for this:

PYTHONPATH=. python my_file.py

which tells python to look for modules to import in ., or:

sys.path.append(os.path.dirname(__file__))

which modifies the import path on runtime, adding the directory of the 'current' file.

akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
  • 1
    Yes, glglgl is right, see [here](http://docs.python.org/2/library/sys.html#sys.path) – pradyunsg Mar 28 '13 at 12:23
  • Ah it seems you're right, sorry guys, my experience is colored by often invoking scripts within a module from a directory higher which screws with the "directory containing the script that was used to invoke the Python interpreter". – akaIDIOT Mar 28 '13 at 14:15
0

1st option: Add the path to your files to the default paths Pythons looks at.

import sys
sys.path.insert(0, 'C:/complete/path/to/my/directory')

2nd option: Add the path relative to your current root of your environment (current directory), using instead the following:

#Learn your current root 
import os
os.getcwd()  

#Change your current root (optional)
os.chdir('C:/new/root')

#Add the path from your current root '.' to your directory
import sys
sys.path.insert(0, './Path/from/current/root/to/my/directory')