Adapting code from Python 2.7 to 3.5 [duplicate] - python

I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the import command again won't do anything.
Executing reload(foo) is giving this error:
Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
What does the error mean?

reload is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected.
If you truly must reload a module in Python 3, you should use either:
importlib.reload for Python 3.4 and above
imp.reload for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of importlib)

For >= Python3.4:
import importlib
importlib.reload(module)
For <= Python3.3:
import imp
imp.reload(module)
For Python2.x:
Use the in-built reload() function.
reload(module)

import imp
imp.reload(script4)

To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3

I recommend using the following snippet as it works in all python versions (requires six):
from six.moves import reload_module
reload_module(module)

For python2 and python3 compatibility, you can use:
# Python 2 and 3
from imp import reload
reload(mymodule)

If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).
import sys
if(sys.version_info.major>=3):
def reload(MODULE):
import importlib
importlib.reload(MODULE)
BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....

Related

No module named titlecase (existence confirmed)

I tried to use the package called "titlecase" (https://pypi.python.org/pypi/titlecase)
My code works on jupyter notebook but it does not work when I tried to run it in cmd.
Here is my code:
from __future__ import print_function
import datetime
now = datetime.datetime.now()
from titlecase import titlecase
f=open(r'C:\Users\GX\everyFirstLetterCapitalized.txt')
f.seek(0)
message = f.read()
outPut=titlecase(message)
f=open(r'C:\Users\GX\everyFirstLetterCapitalizedOutput.txt', 'w')
f.write("new output:-- {a}\n".format(a=now)+outPut)
f.close()
But, I always got the result:
ImportError: No module named titlecase
I tried to use the following code to find the package, it does exist:
import imp
imp.find_module('titlecase')
1 of 2 things:
Do you have more than one installations of python. If so never just use pip. use pip<pythonversion> for example pip3 install etc. if you have 2 versions of python 3.x or 2.x, then do pip3.x install ... (or 2.x)
2 of 2 things, Whats your path? system and python paths are needed to solve module import issues, otherwise we can't help you.
Try reinstalling using the method in section 1.

Python import Error: from .decoder import JSONDecoder: invalid syntax

I have a python module (getActiveLocation.py). It basically makes a http POST call, processes its response and returns it.
It makes use of json module. I am running python 2.6 on RedHat Linux. This module works fine when it is run standalone.
When the module getActiveLocation.py is run standalone, sys.path is
['/current_directory/','/usr/lib64/python26.zip','/usr/lib64/python2.6','/usr/lib64/python2.6/lib-tk','/usr/lib64/python2.6/site-packages','/usr/lib/python2.6/site-packages']
json module is existing within /usr/lib64/python2.6/ directory.
This python module (getActiveLocation.py) is imported inside a jython script (schedule_location.py) and when jython script is run, it is giving an import error for json module.
ImportError: no module named json
It looks like a sys.path issue.
I tried manually adding /usr/lib64/python2.6 to sys.path inside schedule_location.py via:
sys.path.append('/usr/lib64/python2.6')
Then the error changed to:
File "/usr/lib64/python2.6/json/__init__.py", line 108
from .decoder import JSONDecoder
^
SyntaxError: invalid syntax
Any idea why this error is happening? Your help is appreciated.
Vasily,
I am on a production system where I do not have any control! So upgrading jython is not an immediate solution for me :(.
I used simplejson as mentioned in the comment in Portable json module in jython
But here again, it is working when I run it in python. But when run from jython, it gives:
File "schedule_location.py", line 21, in ?
File "getActiveLocation.py", line 4, in ?
File "simplejson/__init__.py", line 113, in ?
File "simplejson/decoder.py", line 7
from .compat import fromhex, b, u, text_type, binary_type, PY3, unichr
^
SyntaxError: invalid syntax
To overcome this, I used:
from __future__ import absolute_import
But it gave:
File "schedule_location.py", line 21, in ?
File "getActiveLocation.py", line 1
SyntaxError: future feature absolute_import is not defined
I understand that this requires python 2.5 or more. But I am on Python 2.6
Probably you need
from __future__ import absolute_import
to make your code compatible with Python 3.x style imports.
Or try to remove "dot": from decoder import JSONDecoder. It should work in Python 2.6. Not sure about Jython.
EDIT: Found answer in the comment here: Portable json module in jython
I had the same SyntaxError when running a python script from a bash script. The solution was to specify the PYTHONPATH, e.g. PYTHONPATH = /usr/local/lib/python2.7. I also specified which python to use when running the python script, e.g. /usr/local/bin/python my_python_script.py.

Python: "import posix" question

If I import os module, I can run the following to infer the location of os.py
>>> import os
>>> print os.__file__
/usr/lib/python2.6/os.pyc
However, when I import posix, it does not have the __file__ attribute. Is it because it is implemented as a part of the python runtime, not as a standard library?
How can I find out more information like this using solely the python official documentation?
It's a C module. It can be either built into the Python binary or compiled as a shared library. In your case it is compiled in
The official docs say not to import it directly, and you should use the functionality provided via os
Run python interactively.
>>> import posix
>>> help(posix)
There's a lot of good stuff there.
FILE
(built-in)
You can also use the 'inspect' module to find information (say source file path etc) about a python module. For example:
import inspect
import os
inspect.getsourcefile(os)
'/usr/local/lib/python2.7/os.py'
inspect.getsourcefile(inspect)
'/usr/local/lib/python2.7/inspect.py'
import sys
inspect.getsourcefile(sys)
Traceback (most recent call last):
[...]
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module 'sys' (built-in)> is a built-in module

python2.7:A sample script ,in C partition it can run however in D partition it has AttributeError

I am learning python. Today I meet with a odd problem.
from urllib import urlopen
url='http://www.google.com'
f=urlopen(url).read()
print f
It is a sample script ,it can run if it in C partition however in D partition
it has AttributeError:
Traceback (most recent call last):
File "D:\urlopen.py", line 1, in <module>
from urllib import urlopen
File "D:\urllib.py", line 7, in <module>
nettext=urllib.urlopen(strurl).read()
AttributeError: 'module' object has no attribute 'urlopen'
I installed python2.7 and python3.1 in win7,and I run the script in python2.7's shell.
I don't know why it works on C:\. It should fail either way. You're importing something from urllib. Your script is called urllib. The current directory comes before standard library dirs, so you import yourself. It's only because imports are "cached" (a second import x in the same interpreter process just gives a reference to the already imported module instead of loading it again) that this doesn't lead to an infinite loop. Of course your module doesn't have anything that's in the stdlib urllib package, e.g. no urlopen.
In Python 3 many modules were reorganized. One of them happens to be urllib. To get the above code to work in Python 3 you would want to do:
import urllib.request
url = "http://www.google.com"
f = urllib.request.urlopen(url).read()
print(f)
Edit:
You will also notice that in Python 3 you must use parentheses with print. For a list of changes from Python 2.x to 3.x, see this documentation
If you are not trying to run this code in Python 3.1 but in 2.7 instead, then it seems your "D partition" is pointing to your Python 3.1 install, whereas your "C Partition" is pointing to 2.7. Python 2.x and 3.x is typically not compatible (see above documentation).

Reloading module giving NameError: name 'reload' is not defined

I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the import command again won't do anything.
Executing reload(foo) is giving this error:
Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
What does the error mean?
reload is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected.
If you truly must reload a module in Python 3, you should use either:
importlib.reload for Python 3.4 and above
imp.reload for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of importlib)
For >= Python3.4:
import importlib
importlib.reload(module)
For <= Python3.3:
import imp
imp.reload(module)
For Python2.x:
Use the in-built reload() function.
reload(module)
import imp
imp.reload(script4)
To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
I recommend using the following snippet as it works in all python versions (requires six):
from six.moves import reload_module
reload_module(module)
For python2 and python3 compatibility, you can use:
# Python 2 and 3
from imp import reload
reload(mymodule)
If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).
import sys
if(sys.version_info.major>=3):
def reload(MODULE):
import importlib
importlib.reload(MODULE)
BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....

Categories