I'm doing something basic with python, and I'm getting a pretty common error, but not able to find exactly what's wrong. I'm trying to use a custom module (built by someone else). I have the folder structure like this:
There is the test folder, and I have a file testing.py within that:
The contents of testing.py is:
from util import get_data, plot_data
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
When I run this file, using python testing.py, I get this:
I went through the other questions that speak about paths, and this looks fine, so not sure what I am missing here. My environment is setup using conda, and the environment is active.
EDIT
As per #allan-wind, I made the relative edit, which got me past the error, but now getting different errors:
I tried the relative import, and it got past that error, but then it is now throwing this error:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 190, in get_context
ctx = _concrete_contexts[method]
KeyError: 'fork'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "grade_analysis.py", line 21, in <module>
from grading.grading import (
File "E:\_Repo\GT\CS7646\mls4tsp23\grading\grading.py", line 15, in <module>
multiprocessing.set_start_method('fork')
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 246, in set_start_method
self._actual_context = self.get_context(method)
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 238, in get_context
return super().get_context(method)
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 192, in get_context
raise ValueError('cannot find context for %r' % method)
ValueError: cannot find context for 'fork'
`
There are a number of ways to specify how to find modules:
Use a relative import:
from .util import get_data, plot_data
Set the environment variable PYTHONPATH includes the directory where you module resides.
See sys.meta_path
Just place utils in the same folder as your testing.py and the python interpreter you put that directory in your path. Other solutions would be to place utils in a directory that is already in your path, since if thats not the case, you cant import from "above" the current directory
Related
import tailer
test = tailer.tail(open("test.txt"), 1)
#print(lines[1])
It's as simple as the code above, but it doesn't work.
(I saved it because it was successful once during the experiment, but an error occurs when I run it again later.)
Error content:
Traceback (most recent call last):
File "c:\Users\user\Documents\VSCODE\python\V1\tailer.py", line 1, in <module>
import tailer
File "c:\Users\user\Documents\VSCODE\python\V1\tailer.py", line 3, in <module>
test = tailer.tail(open("test.txt"), 1)
AttributeError: partially initialized module 'tailer' has no attribute 'tail' (most likely due to a circular import)
Looks like your file is called tailer.py, so when it does import tailer, it tries to load itself, which is usually a recipe for confusion.
You named your program tailer.py. When you do an import tailer the local folder has priority over all other folders and you will import tailer.py again. Creating an import circle.
In other words: you have a name clash between your program and the library you are trying to import. Just rename the file to something else and try again.
This is my Python code:
from plugin import Plugin
import logging
import yaml
log = logging.getLogger('discord')
def get_bot_prefix():
with open('HarTex/hartexConfig.yaml', 'r') as prefixReader:
prefixValue = yaml.safe_load(prefixReader)
prefixString = prefixValue['settings']['prefix']
return prefixString
prefix = get_bot_prefix()
However I got an error with the file accessing:
Traceback (most recent call last):
File "C:/Users/85251/Documents/Discord Bots/Python/HarTex/bot.py", line 20, in <module>
from plugins.help import Help
File "C:\Users\85251\Documents\Discord Bots\Python\HarTex\plugins\help.py", line 30, in <module>
prefix = get_bot_prefix()
File "C:\Users\85251\Documents\Discord Bots\Python\HarTex\plugins\help.py", line 22, in get_bot_prefix
with open('HarTex/hartexConfig.yaml', 'r') as prefixReader:
FileNotFoundError: [Errno 2] No such file or directory: 'HarTex/hartexConfig.yaml'
How can I fix it? Or am I completely wrong with the directory?
The script should work if you are calling it from the parent directory of HarTex, maybe you are running it from a different working directory?
You could also try to open the file using the full path, as this is probably easy to check.
Error is very clear.You should use absolute path instead of relative path.
For an example home/Prakash/Desktop/test12/test.yaml
Your code definitely work,Once you will change path like this.
To run one of my script I have to use the shapely python package, but it crashes because it cannot load the libgeos library. It gives me the following error message:
Traceback (most recent call last):
File "download_nl.py", line 2, in <module>
from download_sentinel import sentinel_available, sentinel_download, download_orbits
File "/nfs/home2/gmulder/radar_database/download_sentinel.py", line 14, in <module>
from fastkml import kml
File "/home/gmulder/python_packages/fastkml/__init__.py", line 30, in <module>
from .kml import KML, Document, Folder, Placemark
File "/home/gmulder/python_packages/fastkml/kml.py", line 37, in <module>
from .geometry import Geometry
File "/home/gmulder/python_packages/fastkml/geometry.py", line 23, in <module>
from shapely.geometry import Point, LineString, Polygon
File "/home/gmulder/python_packages/shapely/geometry/__init__.py", line 4, in <module>
from .base import CAP_STYLE, JOIN_STYLE
File "/home/gmulder/python_packages/shapely/geometry/base.py", line 9, in <module>
from shapely.coords import CoordinateSequence
File "/home/gmulder/python_packages/shapely/coords.py", line 8, in <module>
from shapely.geos import lgeos
File "/home/gmulder/python_packages/shapely/geos.py", line 73, in <module>
_lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
File "/home/gmulder/python_packages/shapely/geos.py", line 68, in load_dll
libname, fallbacks or []))
OSError: Could not find lib geos_c or load any of its variants ['libgeos_c.so.1', 'libgeos_c.so'].
However, the strange thing is that, when I run python interactively, the import goes fine and I do not get any errors. To check whether it is a problem with setting the right paths, I also checked the source. The original code is the following, where the libname gives the library name.
def load_dll(libname, fallbacks=None, mode=DEFAULT_MODE):
lib = find_library(libname)
dll = None
print(sys.version)
dirname = '/hpc/sw/geos-3.5.0/lib'
os.environ['PATH'] = dirname + os.pathsep + os.environ['PATH']
if os.path.exists(os.path.join(dirname, 'libgeos_c.so.1')):
print('library does exist!')
os.chdir(dirname)
if lib is not None:
try:
LOG.debug("Trying `CDLL(%s)`", lib)
dll = CDLL(lib)
except OSError:
LOG.warn("Failed `CDLL(%s)`", lib)
pass
if not dll and fallbacks is not None:
for name in fallbacks:
try:
LOG.debug("Trying `CDLL(%s)`", name)
dll = CDLL(name)
except OSError:
# move on to the next fallback
LOG.warn("Failed `CDLL(%s)`", name)
pass
print(dll)
if dll:
LOG.debug("Library path: %r", lib or name)
LOG.debug("DLL: %r", dll)
return dll
else:
# No shared library was loaded. Raise OSError.
raise OSError(
"Could not find lib {0} or load any of its variants {1}.".format(
libname, fallbacks or []))
To check whether the needed lib file location can be found by the code I added an extra check at line 7, which confirms the library is there. But then, when I try to load it, nothing is loaded, even if I feed the full path to the CDLL function directly.
I also tried to load the library by running python and opening the library interactively (not from a python script), which worked fine. Therefore, I checked the python versions, because I thought that could maybe cause this problem. But the python versions for my script and the interactive session are the same. Can someone help me with this? Likely I missed something, but I have no idea what is causing this problem.
When I run my code from main, it runs perfectly fine, but when I try to build main into an exe using py2exe, it gives this error:
Traceback (most recent call last):
File "main.py", line 118, in <module>
menu.menu.Menu()
File "menu\menu.pyo", line 20, in __init__
File "settingsManager.pyo", line 61, in getSetting
File "settingsManager.pyo", line 148, in __init__
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\Users\\digiholic\\git\\universalSmashSystem\\main.exe\\settings\\rules/*.*'
The line it's referring to is:
for f in os.listdir(os.path.join(os.path.dirname(__file__),'settings','rules')):
It looks like os.listdir is using unix file pathing to find every file, and Windows is having none of that. Is there a way to use listdir in a way that won't blow up everything?
When you're running within the exe you need to check if the module is frozen, the path from __file__ is generally not what you expect when you're within an exe vs the raw python script. You need to access the location with something like this:
import imp, os, sys
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
Source: http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe
You can also check another direction here: http://www.py2exe.org/index.cgi/WhereAmI
Hi I've installed pynsist in order to make my python files into executables but I am having some issues. The project consists of two files that I've written. The main program to be run is Filereader.py and a supplied file called spuriousReq.py which Filereader.py uses a function from. Currently my installer.cfg file looks like this
[Application]
name=WFilereader
version=1.0
entry_point=Filereader
console=true
[Python]
version=3.4.0
[Include]
packages = matplotlib
statistics
bisect
files = spuriousReq.py
I've moved the installer.cfg file and both python files to the C:\Python34\Scripts folder in order to access them from the cmd (Yes I am new at this..). But I get the following error which I dont know how to interpret or solve..
C:\Python34\Scripts>"C:\Python34\python.exe" "C:\Python34\Scripts\\pynsist" inst
aller.cfg
Traceback (most recent call last):
File "C:\Python34\Scripts\\pynsist", line 3, in <module>
main()
File "C:\Python34\lib\site-packages\nsist\__init__.py", line 393, in main
shortcuts = configreader.read_shortcuts_config(cfg)
File "C:\Python34\lib\site-packages\nsist\configreader.py", line 172, in read_
shortcuts_config
appcfg = cfg['Application']
File "C:\Python34\lib\configparser.py", line 937, in __getitem__
raise KeyError(key)
KeyError: 'Application'
As mentioned in the documentation [http://pynsist.readthedocs.io/en/latest/] you need to specify the function from your 'Filereader.py' file which will be starting the execution of your script. For example if you have a 'main' function that will be the entry point or starting point of your script then you need to specify that in your 'installer.cfg' file like below:-
[Application]
name=WFilereader
version=1.0
entry_point=Filereader:main <------ Here mention your entry point function.
console=true
[Python]
version=3.4.0
[Include]
packages = matplotlib
statistics
bisect
files = spuriousReq.py