python go up 2 directories gives syntax error - python

I am making a script (python) and need to import other files (complete).
The file I would like to import, is 2 directories up from the script.
Normal in Python you would do something like
../../../file.py <-- goes up 3 directories
When I do this in Python it gives a syntax error.
..file for example works but as soon as I chain it ../..file.py the syntax error comes in.
I tried
../..file
../../file
/../..file
/../../file
The error says invalid syntax.
The complete command is
from ../..file import *
I would like to import all the content of the file.
The path needs to be relative due to the nature of the script. No hardcoding allowed.
How can I go up multiple directories in Python?

importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
If you want to import the whole file you can just do import file. Then you can choose the function that you are interesting in.
for example:
import FULL_PATH_TO_MY_FILE
my_file.my_func...
or you can try:
from FULL_PATH_TO_MY_FILE import *
and then you can use each function in your file like this - myfunc()

Related

Cannot import function from another file

I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.
My hotel_helper.py file:
def demo1():
print('\n\n trying to import this function ')
My other file:
from hotel.helpers.hotel_helper import demo1
demo1()
but I get:
ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'
When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.
If you filename is hotel_helper.py you have to options how to import demo1:
You can import the whole module hotel_helper as and then call your func:
import hotel_helper as hh
hh.demo1()
You can import only function demo1 from module as:
from hote_helpers import demo1
demo1()
From your fileName import your function
from hotel.helpers import demo1
demo1()
You can import a py file with the following statement:
# Other import
import os
import sys
if './hotel' not in sys.path:
sys.path.insert(0, './hotel')
from hotel import *
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html
This is probably a duplicate of: https://stackoverflow.com/posts/57944151/edit
I created two files (defdemo.py and rundefdemo.py) from your posted 2 files and substituted 'defdemo' for 'hotel.helpers.hotel_helper' in the code. My 2 files are in my script directory for Python 3.7 on windows 10 and my script directory is in the python path file python37._pth. It worked.
defdemo.py
def demo1():
print('\n\n trying to import this function ')
rundefdemo.py
from defdemo import demo1
demo1()
output
trying to import this function
I was able to solve the issue, it was related to some imports I was making in my file, when I removed all the import statement in my hotel_helper.py ,the code started working as expected , Still I don't understand reason why the issue was occurring. anyway it works.
This ImportError can also arise when the function being imported is already defined somewhere else in the main script (i.e. calling script) or notebook, or when it is defined in a separate dependency (i.e. another module). This happens most often during development, when the developer forgets to comment out or delete the function definition in the body of a main file or nb after moving it to a module.
Make sure there are no other versions of the function in your development environment and dependencies.

how to import scripts as modules in ipyhon?

So, I've two python files:
the 1st "m12345.py"
def my():
return 'hello world'
the 2nd "1234.py":
from m12345 import *
a = m12345.my()
print(a)
On ipython I try to exec such cmds:
exec(open("f:\\temp\\m12345.py").read())
exec(open("f:\\temp\\1234.py").read())
the error for the 2nd command is:
ImportError: No module named 'm12345'
Please, help how to add the 1st file as a module for the 2nd?
First off, if you use the universal import (from m12345 import *) then you just call the my() function and not the m12345.my() or else you will get a
NameError: name 'm12345' is not defined
Secondly, you should add the following snippet in every script in which you want to have the ability of directly running it or not (when importing it).
if "__name__" = "__main__":
pass
PS. Add this to the 1st script ("m12345.py").
PS2. Avoid using the universal import method since it has the ability to mess the namespace of your script. (For that reason, it isn't considered best practice).
edit: Is the m12345.py located in the python folder (where it was installed in your hard drive)? If not, then you should add the directory it is located in the sys.path with:
import sys
sys.path.append(directory)
where directory is the string of the location where your m12345.py is located. Note that if you use Windows you should use / and not \.
However it would be much easier to just relocate the script (if it's possible).
You have to create a new module (for example m12345) by calling m12345 = imp.new_module('m12345') and then exec the python script in that module by calling exec(open('path/m12345.py').read(), m12345.__dict__). See the example below:
import imp
pyfile = open('path/m12345.py').read()
m12345 = imp.new_module('m12345')
exec(pyfile, m12345.__dict__)
If you want the module to be in system path, you can add
sys.modules['m12345'] = m12345
After this you can do
import m12345
or
from m12345 import *

Python Import Module on Raspberry Pi

I know this has been asked dozens of times but I can't see what in the world I'm doing wrong. I'm trying to import a module in python 2.7 from a different directory. I would greatly appreciate some input to help me understand why this method doesn't work. I have the following directory structure on my raspbian system:
/home/pi/
...projects/__init__.py
...projects/humid_temp.py
...python_utilities/__init.py__
...python_utilities/tools.py
I'm calling humid_temp.py and I need to import a function within tools.py This is what their contents look like:
humid_temp.py:
import os
import sys
sys.path.append('home/pi/python_utilities')
print sys.path
from python_utilities.tools import *
tools.py:
def tail(file):
#function contents
return stuff
The print sys.path output contains /home/pi/python_utilities
I'm not messing up my __init__.py's am I?
I've also ruled out possible permission issues with that path as I gave it full 777 access and I still hit the
ImportError: No module named python_utilities.tools.
What did I miss?
When you want to import something like -
from python_utilities.tools import *
You need to add the parent directory of python_utilities to sys.path , not python_utilities itself. So, you should add something like -
sys.path.append('/home/pi') #Assuming the missing of `/` at start was not a copy/paste mistake
Also, just a note, from <module> import * is bad , you should consider only importing the required items, you can check the question - Why is "import *" bad? - for more details.
In humid_temp.py, just write:
from python_utilities import tools
There is no need for appending subfolder to sys.path.
Then when you want to use functions from tools, just
tools.function()

Import Python file from within executing script

I am attempting to import a python file(called test.py that resides in the parent directory) from within the currently executing python file(I'll call it a.py). All my directories involved have a file in it called init.py(with 2 underscores each side of init)
My Problem: When I attempt to import the desired file I get the following error
Attempted relative import in non-package
My code inside a.py:
try:
from .linkIO can_follow # error occurs here
except Exception,e:
print e
print success
Note: I know that if I were to create a file called b.py and import a.py(which in itself imports the desired python file) it all works, so whats going wrong?
For eg:
b.py:
import a
print "success 2"
As stated in PEP 328 all import must be absolute to prevent modules masking each other. Absolute means the module/package must be in the module-path sys.path. Relative imports (thats the dot for) are only allowed intra-packages wise, meaning if modules from the same package want to import each other.
So this leave you with following possibilities:
You make a package (which you seem to have made already) and add the package-path to sys. path
you just adjust sys.path for each module
you put all your custom modules into the same directory as the start-script/main-application
for 1. and 2. you may add a package/module to sys.path like this:
import sys
from os.path import dirname, join
sys.path.append(dirname(__file__)) #package-root-directory
or
module_dir = 'mymodules'
sys.path.append(join(dirname(__file__), module_dir)) # in the main-file
BTW:
from .linkIO can_follow
can't work! The import statement is missing!
As a reminder: if using relative imports you MUST use the from-version: from .relmodule import xyz. An import .XYZ without the from isn't allowed!

Simplest way to Import a shared python script relative to the current script

I am trying to import one python script from another. I have a few common functions defined in one script and then lots of other scripts that want to import those functions. No classes, just functions.
The importing script needs to import from a relative path e.g. ../../SharedScripts/python/common.py
I then a have a few functions def f1(...) defined which I will call.
I found the imp module which seemed to be the right thing to use but I was unable to figure out the exact syntax that would work for my example.
Can someone suggest the correct code to use or the simplest approach if imp is not the right module?
SOLUTION from the answers below I was able to get this working...
projectKey = 'THOR'
# load the shared script relative to this script
sys.path.append(os.path.dirname(__file__) + '/../../SharedScripts/python')
import jira
jira.CheckJiraCommitMessage(sys.argv[1], sys.argv[2], projectKey)
Where I had an empty __init__.py and a jira.py in the SharedScripts/python directory with plain function definitions.
Why not adding ../../SharedScripts/python/ to the python path? Then you could use common.py like any other module:
import common
common.f1()
You can alternate the Python path through the system variable PYTHONPATH or by manipulating it directly from python: sys.path.append("../../SharedScripts/python/")
Please notice that it is probably wiser to work with absolute pathes... (The current directory of the app could change)
To get the absolute path could can call use the function os.path.abspath: os.path.abspath('../../SharedScripts/python/')
A possible way is to add the directory to the Python path before doing the import.
#!/usr/bin/env python
import sys
sys.path.append('../../SharedScripts/python')
import common

Categories

Resources