So the issues that I am currently hitting is with the use of __import__ and even just the standard import. When importing multiprocessing just the main package it will go through however when I run a simple test to see if everything is working for it. I come across an error, below is the current code that IS NOT working.
__import__('multiprocessing')
def my_function():
print('Hello World')
if __name__ == '__main__':
processd = multiprocessing.Process(target=my_function)
processd.start()
processd.join()
it run it will return the following error:
Traceback (most recent call last):
File "F:\Webserv\Python\MP.py", line 7, in <module>
processd = multiprocessing.Process(target=my_function)
NameError: name 'multiprocessing' is not defined
Is there something I am missing with this?
__import__ is a function, therefore you need to capture its return value:
multiprocessing = __import__('multiprocessing')
The standard way is to use the import statement:
import multiprocessing
This is the preferred way. Do programmatic imports only when you really need them. Furthermore, __import__ should not be used:
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
Related
I want to get the .exe file from a code source but doing python main.py build results in this error:
C:\MyProject>python main.py build
Traceback (most recent call last):
File "main.py", line 5, in <module>
import parserz as parser
File "C:\MyProject\parserz.py", line 9
import * from modbus
^
SyntaxError: invalid syntax
Any idea please?
Maybe a problem with pip?
In python you import like this
from modbus import *
Also, In python its good practice to import only what you need.
So you shouldn't use from .... import * instead use
from modbus import something
You can either import the module and run all normal code with
import modbus
or you can import all the classes, functions, variables, etc., from the file to use later in your code with
from modbus import *
To illustrate my point:
If you have two files my_imports.py and main.py that contain the following code:
my_imports.py:
print('Imported module my_imports')
def add_nums(a,b):
return a+b
def another_function():
return 'this function was also called'
(version 1) main.py:
import my_imports
# this code would fail because the function isn't imported
print(add_nums(5,7))
(version 2) main.py:
from my_imports import *
print(add_nums(5,7))
print(another_function())
In verion 1 of main.py you would see Imported module my_imports in the output but your code would fail when you try to use the
add_nums function defined in my_imports.py.
In version 2 of main.py you would still see Imported module my_imports in the output but you would also see the result of calling the other two functions in the output as they are now available for use in main.py:
12
this function was also called
As mentioned in some of the other answers, you can also just import the functionality you want from another python script. For example, if you only wanted to use the add_nums method, you could instead have
from my_imports import add_nums
in your main.py.
Generally from modbus import * should be enough. But it is generally not a good idea to import all so I recommend import modbus as mb. Also you might want to look into modbus libraries like pyModbus or minimalModbus. Here's a good link depicting their pros and cons: Python modbus library
Let me first establish what working scenario.
main.py
module/file1.py
module/file2.py
main.py
import module.file1
print(module.file1)
module/file1.py
import module.file2
module/file2.py
import module.file1
Running python3 main.py gives me the following, which is fine.
<module 'module.file1' from '/project/module/file1.py'>
Now, if I change module/file2.py to have the following:
import module.file1 as testtt
I get this new output (error):
Traceback (most recent call last):
File "main.py", line 1, in <module>
import module.file1
File "/project/module/file1.py", line 1, in <module>
import module.file2
File "/project/module/file2.py", line 2, in <module>
import module.file1 as testtt
AttributeError: module 'module' has no attribute 'file2'
I'm guessing that python doesn't fully evaluate the imported module when simply importing, causing the circular reference to blow up only when you immediately use it within either of the two files.
I'd imagine I also would not get the error if I used the module in a function, since that would be evaluate when the function is actually called, like this:
import module.file1
def test():
print(module.file1)
What is the recommendation here? Should I just work to remove the circular reference? It seems like code smell anyway (existing code base).
Its an implementation detail. The import statement uses the __import__ function to do the work of finding and importing the module and then binds its returned module to the as testtt variable.
When doing a nested import like import module.file1 as testtt, __import__ returns the base module ("module"). Since the importer still needs to bind "file1" to the local namespace, it has to look up the submodule name "file1" on that object. Since the import of file1 is still in progress, it hasn't been bound to the "module" module yet.
It works in the import module.file1 case because file1 isn't bound to the local namespace and doesn't need a lookup.
There are many pitfalls with circular imports that will bedevil you throughout your code's life cycle. Good luck!
"import" is an executable statement, so you can just do the import inside the function
def test():
import module.file1
print(module.file1)
from os import listdir
modo= [name.split(".py")[0] for name in listdir("scripts") if name.endswith(".py")]
modules = {}
for modu in modo:
modules[modu] = __import__(modu)
test_samp.function("test")
Hello!
If, say "test_samp.py" exists in the scripts directory, why does
this not allow me to run test_samp.function("test")?
It returns:
Unhandled exception in thread started by <function function at 0x8e39204>
Traceback (most recent call last):
File "test_this.py", line 6, in function
test_samp.function("test")
NameError: global name 'test_samp' is not defined
You have two problems in your code:
__import__ doesn't import into global namespace, it returns a module
you're trying to import test_samp while it's scripts.test_samp
What you actually want is:
scripts = __import__("scripts", fromlist=modo)
scripts.test_samp.function("test")
Above __import__ returns scripts package with all the sub-modules loaded. Don't forget to make scripts directory a package by creating __init__.py in it.
See also: Why does Python's __import__ require fromlist?
Your are not defining test_samp you are defining modules['test_samp']. Plus if it's in scripts you need to import scripts.test_samp
in yor case use a package.Add an empty (or not) __init__.py (with 2 underscores). and use import scripts. Access your function with scripts.test_samp.function("test"). And you could use reload(scripts) to reload all of the package.
You can run it using this:
modules["test_samp"].function("test")
So my first python program, I downloaded the macholib package from PYPI, then unzipped it and ran installed the setup.py using python install, now I'm trying to run a program where I first import the macholib, then when I try to access methods like Macho, it gives me an error saying macholib module has no attributes called Macho.
My understanding is macholib is a package and not a module or something, hence I cant use the contents of the package.
Please answer, I've wasted too much time on such a simple newbie issue.
running a mac with the latest version of python.
Code:
import sys
import macholib
MachO(DivXInstaller.dmg)
I tried macholib.MachO(DivXInstaller.dmg) and macholib.MachO.MachO(DivXInstaller.dmg)
Error for python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
MachO(DivXInstaller.dmg)
NameError: name 'MachO' is not defined
You have this line in your code:
MachO(DivXInstaller.dmg)
However, the name MachO is not defined anywhere. So Python tells you this with the error
NameError: name 'MachO' is not defined
If you want to use the MachO module under the name MachO, you have to import it:
from macholib import MachO
This you have not done, which is the cause of your error. All you did was
import macholib
which gives you the name "macholib" that you can use. However, macholib contains mostly submodules which you can not access like that, so that is not particularly useful. If you don't want to pollute the namespace, you can import MachO as
import machlibo.MachO
Which gives you access to the MachO module as macholib.MachO
You haven't defined DivXInstaller.dmg either, so that's going to be your next error. I recommend that you go through a Python tutorial before you start programming in it.
An import statement defines a namespace. Hence, in order to use something defined in the module or package, you need to qualify it. In this case, the module itself is macholib.MachO but you need to dig deeper, to the actual class MachO which, slightly confusingly, has the same name, so you need to import macholib.MachO and use macholib.MachO.MachO (note that when I try to do this I get an error "DistributionNotFound: altgraph", however).
Note further that it takes a filename as an argument, which is a string. Moreover, you are actually creating an instance of a class, so you probably mean
mlib = macholib.MachO.MachO("DivXInstaller.dmg")
where now mlib is actually the object you need to manipulate with further calls...
Alternately you can do from macholib import MachO or even from macholib.MachO import MachO so you could use MachO.MachO(...) or MachO(...) directly.
This is so simple if you understand Python Packages vs. Modules and import vs. from import:
A Python module is simply a Python source file.
A Python package is simply a directory of Python module(s).
1- import:
import package1.package2.module1
To access module1 classes, functions or variables you should use the whole namespace: package1.package2.modlue1.class1
You cannot import a class or function this way: (wrong)
import package1.package2.class1
2- from ... import
Instead use "from" to import a single class, function or variable of a module:
from package1.package2.module1 import class1
no need to address the whole namespace: class1.method1() works now
Note that you cannot import a method of a class this way
Example:
datetime is a class of module datetime that has a method called utcnow(), to access utcnow() one could:
import datetime
datetime.datetime.utcnow()
Or
from datetime import datetime
datetime.utcnow()
im facing typical NameError (without any additional message) on command "cd" while importing other file.
E.g. executor.py
import sys
from java.lang import System
import ds_update
x = ds_update.DataSource()
x.someAction()
And ds_update.py
import sys
from java.lang import System
import sys
from java.lang import System
class DataSource:
def someAction(self):
try:
cd('/')
...
Got error: (if those commands are in one file, there is no problem with cd)
Problem invoking WLST - Traceback (innermost last):
File "...\executor.py", line 17, in ?
File "...\ds_update.py", line 11, in updateDS
NameError: cd
Thank you:-)
You're trying to use a function that isn't defined, namely cd(), according to your comments, it is something provided by WLST. I never used Jython nor WLST, but you have to find a way to import these methods in your script to be able to use them.
there are a few imports needed, namely at least:
import wl
the way to generate the wl module is described by Oracle here http://docs.oracle.com/cd/E15051_01/wls/docs103/config_scripting/using_WLST.html#wp1094333
then you should prefix with "wl." all your "cd" and other WLST built-in commands.
you will find more here
http://www.javamonamour.org/2013/08/wlst-nameerror-cd.html
Even though it is old, I want to add this:
WLST uses a type of namespace. because of this, functions pertaining to wlst don't work if you put the to-be-imported-files not in /wlserver_10.3/common/wlst