how can I import subfolders module python to another file? - python-2.7

I want to access to my modules.module function A in my main , but when I do this I have an error that I cannot import that.. how can I fix it? I Have seen multiples articles but i hadnt a chance, how can I fix this error of importing modules from subfolders?
**/tool
main.py
/google
/modules
__init__.py
module.py**
ImportError: cannot import name google
main.py
#!/usr/bin/python
import sys
import core.settings
from google.modules import google
if __name__ == '__main__':
try:
core.settings.settings()
google()
except KeyboardInterrupt:
print "interrupted by user.."
except:
sys.exit()
module.py
def google():
print 'A'

the easiest way to work this out is have your main.py in your highest directory (it makes sense anyway for main to be there) and if you really want the real main to be in a sub directory have a dummy main at the top level you can call that just calls the actual main, that way python can see your entire directory tree and will know how to import any sub directory.
alternatively
you could add your parent directory to the sys.path:
parent_dir = os.path.realpath(os.path.join(os.getcwd(),'..')))
sys.path.append(parent_dir)
which will add that directory to the places python searches for when you try to import stuff.
but then you will need to keep track of how deep your main is in the directory tree and its a pretty unelegant solution in my opinion

Related

Python 2.7 cannot find module in its search path

I wanted to test the relative import model of Python 2.X
Directory tree:
exercises/
dir1/
dir2/
mod.py
dir3/
mod2.py
mod3.py
mod.py
import sys
print 'in dir1/dir2/mod.py'
path = [name for name in sys.path if 'Frameworks' not in name].
print 'Module search path of mod is:\n' + str(path)
import dir3.mod2
mod2.py
print 'in dir1/dir2/dir3/mod2.py'
import mod3
mod3.py
print 'in dir1/dir2/dir3/mod3.py by relative import'
'mod' would import 'mod2' from 'dir3', which would then import 'mod3'. In Python 3.X, this would fail because the path to 'mod3' is not provided; in Python 2.X, the interpreter searches the same directory containing 'mod2' before searching the rest of the path starting from the top level directory of 'mod'.
This is the error message I get:
MacBook-Pro-9 exercises % python dir1/dir2/mod.py
in dir1/dir2/mod.py
Module search path of mod is:
['Users/arthur/Desktop/learning_python/exercises/dir1/dir2', '/Library/Python/2.7/site-packages']
Traceback (most recent call last):
File "Desktop/learning_python/exercises/dir1/dir2/mod.py", line 8, in <module>
import dir3.mod2
ImportError: No module named dir3.mod2
I know 'dir2' contains 'dir3/mod2', but for some reason, Python can't find it. I'm pretty sure that the syntax for the import statement is correct.
I modified the print statements and changed 'mod2.py' code to read from . import mod3. I edited nothing else, and it ran just fine in Python 3.8 There was no problem finding 'dir3.mod2'
You have to add an empty file inside dir3 named init.py for python to be able to recognize the directory as a Python package directory. If you have these files
dir3/__init__.py
dir3/mod2.py
dir3/mod3.py
You can now import the code in mod2.py and mod3.py as
import dir3.mod2
import dir3.mod3
or
from dir3 import mod2
from dir3 import mod3
If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
Here is the a link.

Compiled console app quits immediately when importing ConfigParser (Python 2.7.12)

I am very new to Python and am trying to append some functionality to an existing Python program. I want to read values from a config INI file like this:
[Admin]
AD1 = 1
AD2 = 2
RSW = 3
When I execute the following code from IDLE, it works as ist should (I already was able to read in values from the file, but deleted this part for a shorter code snippet):
#!/usr/bin/python
import ConfigParser
# buildin python libs
from time import sleep
import sys
def main():
print("Test")
sleep(2)
if __name__ == '__main__':
main()
But the compiled exe quits before printing and waiting 2 seconds. If I comment out the import of ConfigParser, exe runs fine.
This is how I compile into exe:
from distutils.core import setup
import py2exe, sys
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
zipfile = None,
console=['Test.py'],
)
What am I doing wrong? Is there maybe another way to read in a configuration in an easy way, if ConfigParser for some reason doesnt work in a compiled exe?
Thanks in advance for your help!

From module import * is not importing my functions

I am trying to understand how to import code from one file to another. I have two files file1.py and file2.py. I am running code in the first file, and have many variables and functions defined in the second file. I am using from file2 import * to import the code into file1.py. I have no problem using variables defined in file2.py in file1.py, but with functions I am getting NameError: name 'myfunc' is not defined when I try to use the function in file1.py. I can fix this problem by writing from file2 import myfunc, but I thought writing * would import everything from that file. What is the difference for functions versus variables?
I have tried to recreate the setup you have described and it is working OK for me. Hopefully this will give you an idea of how to get it to work.
# file1.py #####################################
import sys
sys.path.append("/home/neko/test/")
import file2
if __name__ == "__main__":
file2.testfunc()
# file2.py ######################################
testvar = 'hello'
def testfunc(): print testvar
For this test I was using python version 2.6.6
Both file1.py and file2.py is in /home/neko/test/

Crontab cannot find the function imported in my python code

i want to import a function from another python code.
It works when i run manually but not in crontab.
So i have this:
file1.py (the main code)
file2.py (contains a function named read())
So i tried this:
file1.py
import file2
url = 'api:v1/stack/alias'
params = urllib.urlencode({'local': file2.read()})
...
So it works when i execute it manually but not when it added in crontag.
After googling i found another solution:
fil1.py
import sys
sys.path.append('/home/pi')
import file2
It works when executed manually but still not by crontab.
So is there another way to do it?
Thank you

Scrapy: No module named test_1.items

Im trying from import items from the .items file with from test_1.items import Items i keep getting the "No module named test_1.items" error. My structure is
test_1/
test_1/test_2/
test_1/scrapy.cfg
test_1/test_2/spiders/
test_1/test_2/ __init__.py
test_1/test_2/items.py
test_1/test_2/pipelines.py
test_1/test_2/settings.py
test_1/test_2/spiders/ __init__.py
test_1/test_2/spiders/today_spider.py
im coding in today_spider after i modify the items.py file and getImportError: No module named... this error. As you see i tried to change the manes not to be identical. i also tryied to start today_spider with __future__ import absolute_import. any advise?
thks a lot for your time