Importing module from another folder. Python 3.3 - import

Pretty new to python. Running linux os
I have a folder folder1 with my main program "main.py"
I have a folder folder2 with my module "module.py"
The module has 2 functions in it function1 and function2
Both folders are in the same folder.
How do I import the module.py from folder2 into my main.py in folder1? or do I have to pick out the individual function from module.py somehow?
preferably just import both functions at once

You can do:
import sys, os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+ '/folder2/')
Then you can import as usual. Please see the answers to a similar question.

Related

Pytest can't find files/modules

I have had a look at several different topics on this matter but can't work out how to apply it to my situation. I don't have an init.py in my test folder and I have tried to use conftest. I have a directory structure like this:
--app
--app.py
--src
--init.py
--module1.py
--module2.py
--module3.py
--configs
--config.json
--non-default-config.json
--tests
--test1.py
--conftest.py
where app.py imports module1, which then imports modules 2&3 (using import src.module2). I load up config.json in all the modules files (and app.py) using:
with open('configs/config.json') as f:
CFG = json.load(f)
This works when I run app.py from the app directory. However, when I run pytest (which I believe should also be referencing from the app directory, since conftest.py is in the app directory) and it imports module1 (using import src.module1), it cannot find configs/config.json, but will find app/configs/config.json. I cannot use this as it will cause my app to break when I run app.py. However, Pytest can find the imports from within the src folder, even though this is on the same level as the configs folder.
If I move the conftest.py outside of the app directory and import module1 using import app.src.module1 then this import succeeds, but the import of module2 inside module1 then fails.
How can I resolve this issue? And is there a better way of structuring my project?
Solved this by running pytest from inside the app folder instead of from the base directory.

ModuleNotFoundError: No module named 'myfile.py'

So I have trawled through other very similar issues and tried many variations but I cannot get this to work.
I have created code in a separate file under the following structure:
/somefolder/ #this is where my main code resides
/somefolder/src/ this is where my myfile.py resides that I want to import.
My main code starts as follows:
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../src'))
import myfile as mine
but then I get teh following error:
ModuleNotFoundError: No module named 'myfile'
Any assistance would be very welcome.
Assuming your current directory is PythonApplication1, you can follow these steps to access myfile module.
create __init__.py file in both PythonApplication1 and
PythonApplication1\src directories
Now import myfile as from src import myfile as mine

ImportError: when importing from a local script library

Does importing from a local script lib work in qpython3?
I have a script I created in the Qpython projects3 directory of qpython.
projects3/MPU6502/
I have my main code here in this directory.
main.py
I have a local subdirectory,
projects3/MPU6502/tiny6502lib/
In this sub directory I have the source code,
RAM_8bit_Memory.py
From my main.py source code I load the library,
#-*-coding:utf8;-*-
#qpy:3
#qpy:console
# import 6502 library module
from tiny6502lib.RAM_8bit_Memory import *
when I execute the library import I get the ERRORL:
"ImportError: No module named tiny6502lib.RAM_8bit_Memory"
Is importing local script libraries broken in qpython3?
org.qpython.py/projects/MPU6502/main.py
org.qpython.py/projects/MPU6502/tiny6502lib/RAM_8bit_Memory.py
This code works perfectly on all other flavors of python3 (windows) and pythonista on ipad.
How do I get this import to work? Or does it not work at all?
thank you,
Just try to insert the following code before importing tiny6502lib.RAM_8bit_Memory
import sys
sys.path.append("/sdcard/qpython/projects3/MPU6502")
?

Why does importing from a module from the current directory only work when within that directory?

Background
I have a Python project with this directory structure:
py/:
db/ __init__.py run.py
py/db:
handle.py __init__.py util.py
The files are simple enough that I'm not sure I need to post them; nevertheless:
py/run.py
from db.handle import Handle
py/db/handle.py:
import util
class Handle:
def __init__(self, x):
self.x = util.addtwo(x)
py/db/util.py:
def addtwo(x):
return x + 2
If I run handle.py from within the db subdirectory, it imports util without error. However, when I run run.py, handle.py fails with an import error. I can guess that handle.py is being run in the py directory (instead of py/db), and putting a call to os.getcwd() in handle.py confirms this. I can fix this problem using sys.path like so (in run.py):
import sys
sys.path.append("db")
from db.handle import Handle
Question
When importing, from a subdirectory, a module that contains imports to other local modules in that directory, why doesn't Python check the current directory of the module making the import statement? In my example, why doesn't Python check the db first when handle.py contains import statements? Is there a PEP that describes this or is it a behavior with an obvious rationale that I missed?
I thought it might be related to PEP 328:
all import statements be absolute by default (searching sys.path only) with special syntax (leading dots) for accessing package-relative imports.
but I'm not sure.
Your import is "absolute" and module names is looked for in the PYTHONPATH, and that typically includes the current directory.
If you want to import a module from the same folder that your module is in, you use a relative import:
from . import util
or
from .util import addtwo

How to import python modules from parent and sibling packages

This (or similar) question has been asked many times before, but none of the solutions offered work in my case.
My project structure is like this :
| project_2
main.py
__init__.py
systems.py
| config
__init__.py
options.py
| database
__init__.py
database.py
entity.py
| tests
__init__.py
test_systems.py
test_options.py
test_database.py
test_entity.py
Obviously I need to import all the modules in the test modules under the tests package. I tried relative imports with the dot syntax:
from ..systems import System
from ..config import options
from ..database.entity import Entity
Returns a ValueError: Attempt relative import in non-package. I have tried that with a package structure where everything (including systems) is in its own package. It fails with the same message.
What really bothers me is that this is supposed to work: PEP 328, but it does not. I really want to avoid having to append the packages to $PYTHONPATH or to use some insane method such as loading the modules with imp from the file path.
I read that part of the problem might be that systems.py is in the main package, but that does not explain why the rest of the relative imports do not work either.
P.S. I actually recreated the example from PEP 328 just to test it and it does not work.
You get that when a python file does a relative import, but that file not loaded as a module via import in another module (but e.g. from the commandline). Given this structure:
.
├── main.py
└── test
├── __init__.py
├── a.py
└── b.py
main.py:
from test.a import A
print A
a.py:
from .b import B
A = B
if __name__ == '__main__':
print A
b.py:
B = 'b'
Now try:
python main.py
result is
b
and with
python test/a.py
you get:
Traceback (most recent call last):
File "test/a.py", line 1, in <module>
from .b import B
ValueError: Attempted relative import in non-package
What does work is:
python -m test.a
If you simply add . to your python path, if you run the script from the project_2 folder relative paths such as config.options will work. This requires an update to PYTHONPATH on every machine, unfortunately.
Tested on Python 2.7.14