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.
+2
A:
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
2009-05-30 23:44:31
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
2009-05-31 00:07:25
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
2009-05-31 00:15:23
alright, I can probably find the rest out when I need to now that I have a direction, thanks again.
Justen
2009-05-31 00:38:58
@Unknown: Wrong. __import__ has nothing to do with importing from a specific directory.
nosklo
2009-06-01 14:23:29
oh yeah imp.load_source is for specific directories while __import__ lets you change the name and global local scope.
Unknown
2009-06-01 20:06:15
+1
A:
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
2009-05-30 23:44:36