What the title says. I have the following file structure inside the pathC:\Users\User\Desktop\all python file\5.0.8:
5.0.8\
tree one\
little main.py
sample_tree1.py
tree two\
sample_tree2.py
the following is what's inside little main.py:
import sys
import sample_tree1
sys.path.insert(0, r'C:\Users\User\Desktop\all python file\5.0.8\tree two\sample_tree2.py')
import sample_tree2
I want to import sample_tree2.py, but an error is raised as soon as I run the little main.py:
Traceback (most recent call last):
File "<ipython-input-1-486a3fafa7f2>", line 1, in <module>
runfile('C:/Users/User/Desktop/all python file/5.0.8/tree one/little main.py', wdir='C:/Users/User/Desktop/all python file/5.0.8/tree one')
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
execfile(filename, namespace)
File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/User/Desktop/all python file/5.0.8/tree one/little main.py", line 12, in <module>
import sample_tree2
ModuleNotFoundError: No module named 'sample_tree2'
So what happened? I followed this post's top answer in order to import a file from another branch of path, but it doesn't work.
Thank you in advance
EDIT:
I am looking for a solution that:
1) does not require changing the current working directory
2) does not require changing the names of the files
3) does not require changing the configuration of the python terminal stuff
EDIT2:
Added some capscreens of files and folder structures, and error messages
The sys.path.insert() command inserts a path into the system path and should not contain the filename.
Please try below using your structure:
little main.py:
import sys
import sample_tree1
sys.path.insert(0, r'/my/absolute/path/5.0.8/treetwo')
print(sys.path) # view the path and verify your insert
import sample_tree2
print(sample_tree2.tree2_func())
sample_tree2.py in treetwo
def tree2_func():
return 'called tree2'
Outputs:
['/my/absolute/path/5.0.8/treetwo', '... other paths']
called tree2
Related
My .py file looks like:
import hy
import example
foo2()
My .hy file looks like:
(defn foo2 [] (+ 1 1))
.hy file is in same folder as .py file.
If I run .py file I am getting error:
runfile('D:/del/hy2/untitled46.py', wdir='D:/del/hy2')
Reloaded modules: example
Traceback (most recent call last):
File "<ipython-input-274-3982ada2f243>", line 1, in <module>
runfile('D:/del/hy2/untitled46.py', wdir='D:/del/hy2')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "D:/del/hy2/untitled46.py", line 3, in <module>
foo2()
NameError: name 'foo2' is not defined
Question: How to correct my code above if I want to call function defined in .hy file from .py file with Python?
By the way this works fine.
In .py file:
import hy
import example
In .hy file:
(print "Hello, World")
Python can't resolve the name foo2 in that context. Maybe you meant from example import foo2? I'm assuming your .hy file is the example module you imported.
I can't program in python at all. I'm just trying to run the grgsm (gnu radio gsm) program, which is written in python. I get following error:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/grgsm/__init__.py", line 48, in <module>
from .grgsm_swig import *
File "/usr/lib/python3.8/site-packages/grgsm/grgsm_swig.py", line 13, in <module>
from . import _grgsm_swig
ImportError: libboost_program_options.so.1.71.0: cannot open shared object file: No such file or directory
Traceback (most recent call last):
File "/usr/bin/grgsm_livemon", line 37, in <module>
from grgsm import arfcn
File "/usr/lib/python3.8/site-packages/grgsm/__init__.py", line 48, in <module>
from .grgsm_swig import *
File "/usr/lib/python3.8/site-packages/grgsm/grgsm_swig.py", line 13, in <module>
from . import _grgsm_swig
ImportError: libboost_program_options.so.1.71.0: cannot open shared object file: No such file or directory
From the above message, I concluded that in the 13th line of the file "/usr/lib/python3.8/site-packages/grgsm/grgsm_swig.py" there is an import of the file "libboost_program_options.so.1.71.0", which is missing. Well, but in the 13th line of this file there is nothing about it. It looks like this:
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.1
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise RuntimeError("Python 2.7 or later required")
# Import the low-level C/C++ module
if __package__ or "." in __name__:
from . import _grgsm_swig # 13th line
else:
import _grgsm_swig
try:
import builtins as __builtin__
except ImportError:
import __builtin__
I also don't know why python wants this version of boost. If I knew where it is imported, I would simply change it to libboost_program_options.so without the version suffix (because of course I have boost installed).
Solution can be found here. Generally, uninstall it and reinstall its dependencies in the correct order.
one of my code lines is
import yaml
which was installed on python 3.7 using pip install pyyaml
the following error arises
Traceback (most recent call last):
File
"C:/code/EPMD/Kodex/Applications/EPMD-Software/Sandbox/peer_changing_send_rate.py",
line 1, in
from TestPeer.TestPeerChangingSendRate import TestPeerChangingSendSpeed
File "C:\code\EPMD\Kodex\Applications\EPMD-Software\TestPeer\TestPeerChangingSendRate.py",
line 1, in
from .TestPeer import TestPeer
File "C:\code\EPMD\Kodex\Applications\EPMD-Software\TestPeer\TestPeer.py",
line 4, in
from BaseProcess.ZmqPeerClass import ZmqPeer
File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ZmqPeerClass.py",
line 2, in
from .ZmqPublisherClass import ZmqPublisher
File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ZmqPublisherClass.py",
line 10, in
from . import ZmqProcessClass
File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ZmqProcessClass.py",
line 5, in
from .ConfigBaseClass import ConfigBase
File "C:\code\EPMD\Kodex\Applications\EPMD-Software\BaseProcess\ConfigBaseClass.py",
line 3, in
import yaml
File "C:\code\EPMD\Kodex\venv\lib\site-packages\yaml__init__.py", line 9, in
from .dumper import *
File "C:\code\EPMD\Kodex\venv\lib\site-packages\yaml\dumper.py", line 6, in
from .representer import *
File "C:\code\EPMD\Kodex\venv\lib\site-packages\yaml\representer.py", line
263, in
SafeRepresenter.add_representer(datetime.date, AttributeError: module 'datetime' has no attribute 'date'
How to I get import yaml to work?
You probably have a file called datetime.py in one of the directories shown in the error message (most probably C:/code/EPMD/Kodex/Applications/EPMD-Software/Sandbox/), if you do then you need to rename it to something that will not shadow any other Python module.
The reasoning is that it masks the actual datetime module, since files/directories/modules in the current working directory have precedence over the modules installed in the site-packages directory (in which the built-in and installed modules live). If both locations contain an a module then import a will import the local a module instead of the (probably) intended a module from site-packages.
When yaml\representer.py did import datetime it imported your datetime.py file/module which does not have a date attribute, which is why an AttributeError was raised when it later tried to use datetime.date.
I have managed to run a simple script located in a 'scripts' folder using 'runscript' from django-extensions. The technique is described here [1] (https://django-extensions.readthedocs.org/en/latest/runscript.html).
The script will run successfully as follows:
python manage.py runscript mysimplescript --script-args Testing 123
Should I now move the script to a sub-folder, then it appears I need to specify the full path to the sub-folder:
python manage.py runscript scripts.myfolder.mysimplescript --script-args Testing 123
I have written a python script which runs successfully when called directly from the command line within its own project folder. The complex script uses a number of additional scripts located within a plethora of sub-folders.
I now want to call this script within django using django-extensions' 'runscript', which means it's being invoked from the 'mysite/' folder where 'manage.py' is located. The script 'mycomplexscript.py' is not in the 'scripts/' folder but relocated to a separate 'myapps/' project folder, along with the sub-folders and scripts.
I've shown the structure below that includes 'mysite/' and some of the sub-folders/files within 'myapp/', notably the module 'myapp/common/types_':
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
scripts
__init__.py
mysimplescript.py
myapps/
__init__.py
mycomplexscript.py
common/
__init__.py
comparison.py
serialisation/
__init__.py
serialisation.py
xml.py
types_/
__init__.py
enum.py
Django-extensions requires that 'mycomplexscript.py' must incorporate a 'run()' function. Line #6 imports a class from one of the project sub-folders:
def run(*script_args):
import os
import sys
import time
from common.serialisation import XML
When calling the script, the error occurs because the module 'common.types_' cannot be located.
python manage.py runscript myapps.mycomplexscript --script-args Testing 123
/usr/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg/django/core/
management/base.py:265: RemovedInDjango110Warning: OptionParser usage for
Django management commands is deprecated, use ArgumentParser instead
RemovedInDjango110Warning)
Exception while running run() in 'myapps.mycomplexscript'
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg/django/core/
management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg/django/core/
management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/
django_extensions/management/email_notifications.py", line 63, in
run_from_argv
super(EmailNotificationCommand, self).run_from_argv(argv)
File "/usr/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg/django/core/
management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/
django_extensions/management/email_notifications.py", line 75, in execute
super(EmailNotificationCommand, self).execute(*args, **options)
File "/usr/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg/django/core/
management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/
django_extensions/management/utils.py", line 57, in inner
ret = func(self, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/
django_extensions/management/commands/runscript.py", line 172, in handle
run_script(mod, *script_args)
File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/
django_extensions/management/commands/runscript.py", line 79, in run_script
mod.run(*script_args)
File "/usr/tester/SwFact/isg_cid-system_test_current/my_site/myapps/
mycomplexscript.py", line 9, in run
from myapps.common.serialisation import XML
File "/usr/tester/SwFact/isg_cid- system_test_current/my_site/myapps/
common/__init__.py", line 7, in <module>
from comparison import Comparison
File "/usr/tester/SwFact/isg_cid-system_test_current/my_site/myapps/
common/comparison.py", line 7, in <module>
from common.types_ import Enum
ImportError: No module named common.types_
The problematic Line #7 in 'comparison.py' is as follows:
from common.types_ import Enum
The error can be fixed if the full path to the root of the project is stated explicitly (+++):
from apps.common.types_ import Enum
This means that I would have to edit all the files and change the paths accordingly, which I'd like to avoid, if possible.
This link [2]:(Python: Referencing another project) describes the referencing another project from the command line, so I realize that this may nothing to do with the fact that I'm trying to do this by using django-extensions' 'runscript'.
Is there a way that I can resolve the path discrepancy, without having to modify all the files? Would setting PYTHONPATH be the answer, as suggested here [3]:(How to use PYTHONPATH)? I checked but 'echo $PYTHONPATH' currently doesn't return anything.
Apologies for the long-winded description.
Thanks in advance.
I tried sys.path.append("my/path") as recommended by link above and [4]:(Python sys.path - appending PYTHONPATH) and it seemed to work, so all the paths included in 'from' are now recognized without having to set the full path, as I described previously here (+++).
myapps/mycomplexscript:
# Procedures
def run(*script_args):
import os
import sys
import time
sys.path.append('/usr/tester/SwFact/isg_cid-system_test_current/
my_site/myapps')
from common.serialisation import XML
from common.task import Subscriber
from test_ import TestHost
from common.filesystem import Directory, File
from common.tables import Column, Condition, CSVTable, Group
from string import Template
from datetime import date, time, datetime, timedelta
from operator import itemgetter
print script_args
So the result when running the script from 'mysite/':
python manage.py runscript myapps.mycomplexscript --script-args Testing 123
/usr/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg/django/core/
management/base.py:265: RemovedInDjango110Warning: OptionParser usage for
Django management commands is deprecated, use ArgumentParser instead
RemovedInDjango110Warning)
('Testing', '123')
It's not ideal to have to hard-code the path this inside the script, so perhaps it can be passed in as one of the arguments. The only problem with this is that imports appear at the top of the file, before any of the command line arguments are processed within the complex script however at least I know it works in principle.
I have created a script to give me the list of files in a folder directory. Yet, I am occasionally getting this error. What does this mean?
portion of the error:
Script failed due to an error:
Traceback (most recent call last):
File "<script>", line 12, in <module>
File "C:\Program Files\Nuix\Nuix 6\lib\jython.jar\Lib\os.py", line 309, in walk
File "C:\Program Files\Nuix\Nuix 6\lib\jython.jar\Lib\os.py", line 299, in walk
File "C:\Program Files\Nuix\Nuix 6\lib\jython.jar\Lib\genericpath.py", line 41, in isdir
File "C:\Program Files\Nuix\Nuix 6\lib\jython.jar\Lib\genericpath.py", line 41, in isdir
java.lang.AbstractMethodError: org.python.modules.posix.PythonPOSIXHandler.error(Ljnr/constants/platform/Errno;Ljava/lang/String;Ljava/lang/String;)V
at jnr.posix.BaseNativePOSIX.stat(BaseNativePOSIX.java:309)
at jnr.posix.CheckedPOSIX.stat(CheckedPOSIX.java:265)
at jnr.posix.LazyPOSIX.stat(LazyPOSIX.java:267)
The script:
import os
import codecs
import shutil
import datetime
import sys
exportpath = 'P:/Output/Export7/{6136BAF2-85BA-4E64-8C11-A2C59398FC02}/'
tempnativefolder = 'NATIVESOrig'
for dir, sub, file in os.walk(exportpath + tempnativefolder):
for fname in file:
#source path
source = os.path.join(dir, fname).replace('\\', '/')
print source
print("Natives moved to subfolders")
I found out that the presence of these characters(see "diamond with question mark" character in screenshot) in the file name causes the issue. Once I replaced those, my script works. thanks so much.
What the error means: AbstractMethodError means that some code tried to call a method which was not implemented.
PythonPOSIXHandler implements jnr.posix.POSIXHandler. JRuby also uses JNR and the interface is subtly different between the two. JRuby's newer copy of JNR has that one additional #error(Errno, String, String) method and Jython's implementation lacks that method, because it's compiled against the interface when the method didn't exist.
I usually see this problem in the other direction - where stuff in Jython's jar breaks JRuby. I assume it entirely depends on the order of the jars in the classpath.