Not able to import module - python

So first... my directory structure..
---script/execute.py
|
L---helper---foo.py
L-----bar.py
L--- __init__.py
Now, execute.py calls both foo and bar .py as
from helper.foo import some_func
I am trying to run this as:
python script/execute.py
But I am getting this import error
from helper.foo import some_func
Import error: No module named helper??
What am I missing (note that there is no init inside script folder??)?
Thanks

You should check out http://docs.python.org/2/tutorial/modules.html#packages
The "too long, didn't read" of it is that you need to have a file called __init__.py in your helper directory, e.g.,
$ touch helper/__init__.py
The file can also contain Python code, but in the simplest form an empty file is ok.

Related

Custom Python module structure

I am currently doing a personal coding project and I am trying to build a module, but I don't know why my structure doesn't work the way it's supposed to:
\mainModule
__init__.py
main.py
\subModule_1
__init__.py
someCode_1.py
someCode_2.py
\subModule_2
__init__.py
otherCode.py
I want to be able to run the following code from main.py:
>>> from subModule_1 import someCode_1
>>> someCode_1.function()
"Hey, this works!"
>>> var = someCode_2.someClass("blahblahblah")
>>> var.classMethod1()
>>> "blah blah blah"
>>> from subModule2 import otherCode
>>> otherCode("runCode","#ff281ba0")
However, when I try to import someCode_1, for example, it returns an AttributeError, and I'm not really sure why. Is it to do with the __init__.py file?
REVISIONS
Minimal, Complete and verifiable (I hope...)
\mainDir
__init__.py # blank file
main.py
\subDir
__init__.py # blank file
codeFile.py
Using this...
#main.py file
import subDir
subDir.codeFile.function()
And this...
#codeFile.py file
def function():
return "something"
...it returns the same problem mentioned above**.
** The exact error is:
Traceback (most recent call last):
File "C:\...\mainDir\main.py", line 2, in <module>
subDir.codeFile.function()
AttributeError: module 'subDir' has no attribute 'codeFile'
Credits to #jonrsharpe: Thanks for showing me how to use Stack Overflow correctly.
You have two options to make this work.
Either this:
from subdir import codeFile
codeFile.function()
Or:
import subdir.codeFile
subdir.codeFile.function()
When you import subDir, it does three things:
executes the code in mainDir/subDir/__init__.py (i.e. in this case does nothing, because this file is empty)
imports the resulting module under the name subDir locally, which will in turn make it an attribute of the mainDir module;
registers the new import globally in the sys.modules dictionary (because the import is being performed from a parent module mainDir, the name is completed to 'mainDir.subDir' for the purposes of this registration);
What it does not do, because it hasn't been told to, is import subDir.codeFile. Therefore, the code in codeFile.py has not been run and the name codeFile has not yet been imported into the namespace of mainDir.subDir. Hence the AttributeError when trying to access it. If you were to add the following line to mainDir/subDir/__init__.py then it would work:
import codeFile
Specifically, this will:
run the code in codeFile.py
add the resulting module as an attribute of the mainDir.subDir module
store a reference to it as yet another entry in sys.modules, this time under the name mainDir.subDir.codeFile.
You could also achieve the same effect from higher up the module hierarchy, by saying import subDir, subDir.codeFile instead of just import subDir in your mainDir.main source file.
NB: When you test this from the command line or IDE, make sure that your current working directory (queried by os.getcwd(), changed using os.chdir(wherever) ) is neither mainDir nor subDir. Work from somewhere else—e.g. the parent directory of mainDir. Working from inside a module will lead to unexpected results.

Call a Python script from a different Python script located at a different location

I have a Python script which is calling a class of another Python script.
The structure of these two scripts are as follows:
c:\testing\sample.py
c:\testing\example\demo\projects\module.py
Now inside sample.py I am calling module.py as follows:
from "c:/testing/example/demo/projects/module.py" import module_C
When I execute this portion of sample.py I get an error There is an error in program and this error occurs in its first line only.
How shall I call the module_C inside sample.py?
the from/import syntax does not work with files, only with modules.
To achieve what you want, there are 2 possibilities
first one: turn traversing directories into modules:
create empty __init__.py files in c:/testing/example/demo, and c:/testing/example/demo/projects,
then from demo.projects.module import module_C
second one: add path dynamically:
import sys,os
sys.path.add(os.path.join(os.path.dirname(__file__),"demo/projects"))
from module import module_C
knowing where you are running, use current module directory and add the demo/projects absolute path: it works because the paths have a common prefix)

Importing __init__

I am trying out the answer in this.
The __init__.py file in a folder named MyLibs contains:
LogFile = r'D:\temp'
In utils.py in the same folder MyLibs, I tried various ways to access the LogFile variable:
from __init__ import *
print LogFile #Gives: NameError: name 'LogFile' is not defined`:
and:
import __init__
print MyLibs.LogFile #Gives: NameError: name 'MyLibs' is not defined
I got the errors while executing from MyLibs.utils import *
What is the fix I must do? I prefer a method where I can reference LogFile directly without having to add namespace prefixes.
My mistake.
The updated __init__.py was somehow not executed. I started a new Python session and it worked.
Sorry for the false alarm.
Not sure how to do this with 2.7's implicit relative imports, but you could try this:
from __future__ import absolute_import
from . import LogFile
If you're running the Python module directly, you need to run it with python -m MyLibs.utils rather than python MyLibs/utils.py.

Python - How to allow the use of a function in different modules?

I have 2 scripts.
Main.py
Update.py
I have a function in Main.py which basically does the following:
def log(message):
print(message)
os.system("echo " + message + " >> /logfile.txt")
And in the Update.py file I have a single function which basically does the update. However throughout the update function, it calls "log(message)" with whatever the message is at that point.
The problem now though is I'm getting a NameError: global name "log" is not defined whenever I try use the function outside of the Main.py script.
Any help? on how I would be able to use the function 'log' wherever?
*Code simplified for explanation.
EDIT:
Main.py imports Update from /Scripts/Update.py
Update.py imports log from Main.py
When i try this, it fails saying "cannot import name Update"
Don't import log from Main. That'll rerun the code in Main.py, since running Main.py as a script and importing it as a module aren't equivalent. Other modules should not depend on functions defined in the main script. Instead, put your log function in another module and import that, or have Main.py explicitly pass a logger to the other modules somehow.
Update: You can't import Update because Python can't find it. Python checks in 4 places for modules to import, but the ones you should be interested in are
the directory the script was from, and
the directories specified in the PYTHONPATH environment variable.
You'll either need to put Main.py and the things it imports in the same directory, or add /Scripts to your PYTHONPATH.
Just add in Update.py the line
from Main import log
and you will be able to call log() from Update.py.
You should import the function:
from Main import log
Or best:
import Main
Main.log()
For modules importing each other, refer How can I have modules that mutually import each other.

Python import module from relative folder

i'm creating a python program, and i want to split it up into seperate files. I'm using import to do this, but its not working (specifically, a variable is stored in one python file, and its not being read by the main one.
program /
main.py
lib /
__init__.py
config.py
functions.py
I have in main.py:
import lib.config
import lib.functions
print(main)
and config.py has
main = "hello"
I should be getting the output "hello", when i'm executing the file main.py, but i'm not. I have the same problem with functions stored in functions.py
Any help would be great,
Importing the module with a simple import statement does not copy the names from that module into your own global namespace.
Either refer to the main name through attribute access:
print(lib.config.main)
or use the from ... import ... syntax:
from lib.config import main
instead.
You can learn more about how importing works in the Modules section of the Python tutorial.

Categories