2

In a simple program I made, I wanted to get a list from another project and access the elements from it. Since I'm new to python, I don't really have any idea what to do. In my project, I checked the box for the project name I wanted to reference and... I don't know what to do. A few google searched did me no good, so I'm hoping someone here can tell/link me how to set this up.

Justen
  • 4,859
  • 9
  • 44
  • 68

3 Answers3

2

Use import. Then you can access the "module" (project) and everything in it like an object./

# a.py
some_list = [1,2,3,4]

# b.py
import a
print a.some_list

If you run b.py, it will print [1,2,3,4]

Unknown
  • 45,913
  • 27
  • 138
  • 182
  • Simple enough, thanks! Also, let's say the .py file I wanted to reference was not in the same directory, would I just include the directory after the import? Like, import c:\python_backup\lists – Justen May 31 '09 at 00:07
  • Justen, it gets more complicated than that. If you want to import a specific directory you need to use the __import__ function. If the directory is a subdirectory of the main file, then you must have an __init__.py file in the subdirectory. Any more explanation about this is too much to fit into this box. – Unknown May 31 '09 at 00:15
  • alright, I can probably find the rest out when I need to now that I have a direction, thanks again. – Justen May 31 '09 at 00:38
  • @Unknown: Wrong. __import__ has nothing to do with importing from a specific directory. – nosklo Jun 01 '09 at 14:23
  • oh yeah imp.load_source is for specific directories while __import__ lets you change the name and global local scope. – Unknown Jun 01 '09 at 20:06
1

Generally if you have some code in project1.py and then want to use it from a different file in the same directory, you can import project1 as a module:

import project1

data = project1.my_data_function()

This works just the same way as you would import any module form the standard library.

sth
  • 222,467
  • 53
  • 283
  • 367
0

Not sure if this will help but I had a similar problem. My problem was the main accessor file was not in the root folder. I had it inside another folder. The reference worked as soon and I moved it to the root folder.

Kaane Guji
  • 115
  • 1
  • 7