I have probably path inaccuracies but can't track it. I have a following statement:
from serial import SerialException
# from Utilities.UnitsFormat import UnitsFormat
from Loggers.MainLogger import NetworkLogger as Logger
import Utilities.Serial.SerialHandle.SerialHandle as SH
It works well on Windows buy fails to find path in Debian Linux:
> root#debian-armhf:/# cd usr/CROW/ATE/Drivers/PSU_PR_V2/
root#debian-armhf:/usr/CROW/ATE/Drivers/PSU_PR_V2# python PSU_PR.py
Traceback (most recent call last):
File "PSU_PR.py", line 79, in <module>
from Loggers.MainLogger import NetworkLogger as Logger
ImportError: No module named Loggers.MainLogger
root#debian-armhf:/usr/CROW/ATE/Drivers/PSU_PR_V2#
How can I resolve this while I remain simple with path management and support both operating systems?
I have tried this with no help:
import os
if os.name == 'nt':
sys.path.append("C:\CROW\ATE")
else:
sys.path.append("usr/CROW/ATE")
Assuming that the file you are manipulating the path from is located some where under the CROW/ATE directory. You could use this code to get a system independent path to that directory like so:
import re
import os
def get_project_dir():
return re.findall(''.join(['.*', os.path.join('CROW', 'ATE')]), os.path.abspath(__file__))[0]
and then do
sys.path.append(get_project_dir())
*I wasn't able to test this on windows but this should be close.
Related
I have 2 folders:
my_python
code.py
MyCode
TestEntry.py
When I run the following commands:
cd /data/my_python
python3 code.py
The above works.
However, if I in my home folder and then run this:
python3 /data/my_python/code.py
I get the following error:
Traceback (most recent call last):
File "/data/my_python/code.py", line 4, in <module>
from TestEntry import TestEntry
ImportError: No module named 'TestEntry'
Here is the code:
import sys
import os
sys.path.append(os.path.abspath('../MyCode'))
from TestEntry import TestEntry
TestEntry().start(507,"My Param1","/param2",'.xyz',509)
Can you help me how to fix this?
You are adding a relative path to sys with your line sys.path.append(os.path.abspath('../MyCode')). Instead, you need to import relative to that file you are calling. Try this:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from TestEntry import TestEntry
TestEntry().start(507, "My Param1", "/param2", '.xyz', 509)
That happens because, as #mkrieger1 mentioned, your sys.path gets messed up. I have a previous answer here which explains how to set it. By sys.path getting messed up, I mean that python will look in the dir that you are running from, not the dir that the script you are running is in. Here is the recommended method:
import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'MyCode')))
... (your code)
or
import sys, os
sys.path.append(os.path.abspath(os.path.join(__file__, '..', 'MyCode')))
... (your code)
This way python will look in the dir of the file you are running as well.
I want to make a file that is consisted of 3 python programs.
but, when I want to access one of the there files from one of them, it cant find the folder.
I made a init python file in it so python can recognize it as a module
my folder struct:
dlgo/
__init__.py
goboard_slow.py
gotypes.py
my goboard_slow:
from dlgo.gotypes import player
error:
Traceback (most recent call last):
File "C:\Users\asus\Desktop\dlgo\goboard_slow.py", line 2, in <module>
from dlgo.gotypes import player
ImportError: No module named 'dlgo'
Access as below:
from dlgo.gotypes import players
See here more info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.
maybe try from (filename) import (functionname)
Tl;dr:
from gotypes.py import player
when you specify path to a file, interpreter starts looking for it inside same folder, unless you give it path from main dirrectory like '/' or 'C:\'
You can import a py file with the following statement:
# Other import
import os
import sys
if './dlgo' not in sys.path:
sys.path.insert(0, './dlgo')
from dlgo.gotypes import player
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 question already has answers here:
import function from a file in the same folder
(4 answers)
Closed last month.
I am trying to separate my script into several files with functions, so I moved some functions into separate files and want to import them into one main file. The structure is:
core/
main.py
posts_run.py
posts_run.py has two functions, get_all_posts and retrieve_posts, so I try import get_all_posts with:
from posts_run import get_all_posts
Python 3.5 gives the error:
ImportError: cannot import name 'get_all_posts'
Main.py contains following rows of code:
import vk
from configs import client_id, login, password
session = vk.AuthSession(scope='wall,friends,photos,status,groups,offline,messages', app_id=client_id, user_login=login,
user_password=password)
api = vk.API(session)
Then i need to import api to functions, so I have ability to get API calls to vk.
Full stack trace
Traceback (most recent call last):
File "E:/gited/vkscrap/core/main.py", line 26, in <module>
from posts_run import get_all_posts
File "E:\gited\vkscrap\core\posts_run.py", line 7, in <module>
from main import api, absolute_url, fullname
File "E:\gited\vkscrap\core\main.py", line 26, in <module>
from posts_run import get_all_posts
ImportError: cannot import name 'get_all_posts'
api - is a api = vk.API(session) in main.py.
absolute_url and fullname are also stored in main.py.
I am using PyCharm 2016.1 on Windows 7, Python 3.5 x64 in virtualenv.
How can I import this function?
You need to add __init__.py in your core folder. You getting this error because python does not recognise your folder as python package
After that do
from .posts_run import get_all_posts
# ^ here do relative import
# or
from core.posts_run import get_all_posts
# because your package named 'core' and importing looks in root folder
MyFile.py:
def myfunc():
return 12
start python interpreter:
>>> from MyFile import myFunc
>>> myFunc()
12
Alternatively:
>>> import MyFile
>>> MyFile.myFunc()
12
Does this not work on your machine?
Python doesn't find the module to import because it is executed from another directory.
Open a terminal and cd into the script's folder, then execute python from there.
Run this code in your script to print from where python is being executed from:
import os
print(os.getcwd())
EDIT:
This is a demonstration of what I mean
Put the code above in a test.py file located at C:\folder\test.py
open a terminal and type
python3 C:\folder\test.py
This will output the base directory of python executable
now type
cd C:\folder
python3 test.py
This will output C:\folder\. So if you have other modules in folder importing them should not be a problem
I usually write a bash/batch script to cd into the directory and start my programs. This allows to have zero-impact on host machines
A cheat solution can be found from this question (question is Why use sys.path.append(path) instead of sys.path.insert(1, path)? ). Essentially you do the following
import sys
sys.path.insert(1, directory_path_your_code_is_in)
import file_name_without_dot_py_at_end
This will get round that as you are running it in PyCharm 2016.1, it might be in a different current directory to what you are expecting...
I'm trying to import module from local path in Python2.7.10 Shell on Windows
I add local path to sys.path by:
import sys
sys.path.append('C:\download')
next I try to import by:
from download.program01 import *
but I've got this error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
from download.program01 import *
ImportError: No module named download.program01
On Linux this code works fine.
Does someone know what is wrong?
If download is in your pythonpath, then you should import program01 directly.
Also, please don't import *; it makes things very hard to debug. Just do import program01.
put a file __init__.py in your download folder so that python knows it is a module and do sys.path.append('C:') instead.
If you want to keep just using path and not create a module file (the __init___.py) then just keep your code like that but import doing
import program01
This may be my own misunderstanding of how Python imports and search paths work, or it may be a problem in the packaging of the caldav package.
I have set up a virtualenv environment named myproject
In the top level of myproject, I have a script test.py which contains two imports:
import lxml
import caldav
In this directory, I type:
python test.py
and it works fine without any problem
Now I move the script to the subdirectory test and run the command:
python test/test.py
The import lxml seems to still work. The import caldav fails with the following exception:
Traceback (most recent call last):
File "test/test.py", line 34, in <module>
main()
File "test/test.py", line 29, in main
exec ( "import " + modulename )
File "<string>", line 1, in <module>
File "/home/ec2-user/caldav2sql/myproject/test/caldav/__init__.py", line 3, in <module>
from davclient import DAVClient
File "/home/ec2-user/caldav2sql/myproject/test/caldav/davclient.py", line 8, in <module>
from caldav.lib import error
ImportError: No module named lib
Am I doing something wrong here? Should I be setting up some kind of path?
Most likely, caldav was in the same directory as test.py, so when you import it it worked fine. Now that you moved test.py to a subdirectory, your imports can't find it. You can either move caldav or set your PYTHONPATH.
You could also modify your sys.path
Information from Python's module tutorial: http://docs.python.org/tutorial/modules.html
The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')