inconsistent behaviour of interactive session and script in Python - python

When I run the script, I had this ImportError:
$ python ~/Dropbox/code/py/ZoteroFindOrphanedFiles.py
Traceback (most recent call last):
File "/home/zane/Dropbox/code/py/ZoteroFindOrphanedFiles.py", line 1, in <module>
import sqlite3
File "/usr/lib/python3.2/sqlite3/__init__.py", line 23, in <module>
from sqlite3.dbapi2 import *
File "/usr/lib/python3.2/sqlite3/dbapi2.py", line 23, in <module>
import datetime
File "/usr/lib/python3.2/datetime.py", line 20, in <module>
import math as _math
File "/home/zane/Dropbox/code/py/math.py", line 3, in <module>
from nzmath.rational import Integer, Rational
ImportError: No module named nzmath.rational
But I don't have it when running the interactive session:
$ python
Python 3.2.3 (default, Apr 23 2012, 23:14:44)
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>>
Why is that?

Here is the problem:
import math as _math
File "/home/zane/Dropbox/code/py/math.py", line 3, in <module>
You have your own module called math.py, but this is the same as a standard Python module of the same name. This is not recommended.
The solution is to rename your math.py to something else, and don't forget to delete the math.pyc in the same directory (otherwise you'll still have the same problem).

You have a local file
/home/zane/Dropbox/code/py/math.py
which is getting imported instead of the standard lib math module.
The solution is to rename your /home/zane/Dropbox/code/py/math.py to something else.
The problem occurs when you call a script in the /home/zane/Dropbox/code/py directory since this adds this directory to the beginning of sys.path and thus this directory gets searched first when Python tries to import modules.

You have a file called math.py in the script's directory, and this shadows the stdlib math module. Rename the file.

Related

Python Import successful but I get NameError

I am running the python interpreter from the same directory where the imported file my_module.py resides. When I try to use the function defined in the imported file using only the function name print_hi, I get a NameError error message. But it works fine if I reference the function using my_module.print_hi
Is there a way to make this work without referencing the module file name?
Is there a way to make this work without using the from keyword in the import statement?
PS C:\Users\joe\Documents\Python\General\importing> type my_module.py
def print_hi(name):
print(f'Hi, {name}')
PS C:\Users\joe\Documents\Python\General\importing> python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_module
>>> print_hi('joe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'print_hi' is not defined
>>> my_module.print_hi('joe')
Hi, joe
>>>
If you want to refer to your print_hi function without using the module name, you must import it explicitly or import everything from the module:
from my_module import print_hi
# or import everything:
from my_module import *
You can use from keyword
from my_module import print_hi
print_hi('Joe')
From is used to import only a specified section from a module.

Trace files/modules loaded when launching python

I am using Paraview 4.0.1 under Ubuntu 14.04 LTS.
But I guess the answer to this question does not necessarily requires knowledge specific to Paraview python.
When I load a python prompt at the command line everything "works well":
$ pvpython
Python 2.7.6 (default, Oct 26 2016, 20:33:43)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from paraview.simple import *
paraview version 4.0.1
>>>
But when I load the python shell within the GUI, from paraview.simple import * fails, either when automatically (at startup) or explicitly imported:
Python 2.7.6 (default, Oct 26 2016, 20:33:43)
[GCC 4.8.4] on linux2
from paraview.simple import *
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paraview/simple.py", line 41, in <module>
import servermanager
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 3157, in <module>
__initialize()
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 3148, in __initialize
c = Connection(iter.GetCurrentSessionId(), iter.GetCurrentSession())
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 1935, in __init__
_createModules(self.Modules)
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 2567, in _createModules
m.filters = createModule('filters')
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 2629, in createModule
if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
AttributeError: 'NoneType' object has no attribute 'GetInformationOnly'
>>> from paraview.simple import *
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paraview/servermanager.py", line 2190, in find_module
if vtkPVPythonModule.HasModule(fullname):
AttributeError: 'NoneType' object has no attribute 'HasModule'
>>>
How can I trace the different sequence of steps taken by each mode of loading a python shell, so as to identify the source of error?
In addition to this manifestation, I found two other differences:
In the command prompt, from paraview.simple import * is not executed automatically, while in the GUI it is. Where is this set?
In the command prompt, having set PYTHONSTARTUP=${HOME}/.pythonrc, which sets import readline, rlcompleter (actually, within a try-except construct), allows for tab completion.
In the GUI, .pythonrc is not read. Why is this? How can I tell the filename which would be read upon startup if it exists?
I have found one option which gives some information, I do not know if it is the only/best one.
Setting
$ export PYTHONVERBOSE=2
(or a different integer for verbosity level [1]) gives a lot of info.
Still, I couldn't find the source of error...

Cannot import logging.py after I renamed one of my source files logging.py in my Eclipse project

I thought, I broke Eclipse by renaming one of my source file logging.py, I quickly changed the name to something else but Eclipse cannot find the original python standard file ... I reinstalled my Anaconda install but it did not correct the problem ... and I later discovered it was likely a Python problem (see Edit 1)
When I ask Eclipse to find or open the file from the 'import logging' line, it seems it cannot find it ...
Any idea to correct this problem without reinstalling Eclipse?
Traceback (most recent call last):
File "C:\Users\ailete\workspace\landema\main.py", line 56, in <module>
import requests
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\__init__.py", line 53, in <module>
from .packages.urllib3.contrib import pyopenssl
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\packages\__init__.py", line 27, in <module>
from . import urllib3
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\packages\urllib3\__init__.py", line 8, in <module>
from .connectionpool import (
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\packages\urllib3\connectionpool.py", line 35, in <module>
from .connection import (
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\packages\urllib3\connection.py", line 43, in <module>
from .util.ssl_ import (
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\packages\urllib3\util\__init__.py", line 19, in <module>
from .retry import Retry
File "C:\Users\ailete\Anaconda2\Lib\site-packages\requests\packages\urllib3\util\retry.py", line 15, in <module>
log = logging.getLogger(__name__)
AttributeError: 'module' object has no attribute 'getLogger'
Edit 1
The problem happens with the executable generated by pyinstaller too ?! :
...
LOADER: Running main.py
Traceback (most recent call last):
File "<string>", line 43, in <module>
File "c:\users\ailete\appdata\local\temp\pip-build-iulqaq\pyinstaller\PyInstaller\loader\pyimod03_importers.py", line 363, in load_module
File "C:\Users\ailete\workspace\landema\entities.py", line 7, in <module>
from config import locale, ribbon_menu
File "c:\users\ailete\appdata\local\temp\pip-build-iulqaq\pyinstaller\PyInstaller\loader\pyimod03_importers.py", line 363, in load_module
File "C:\Users\ailete\workspace\landema\config.py", line 7, in <module>
import logging
ImportError: No module named logging
main returned -1
...
First, define modules path, where built-in module logging is placed:
user#host:$ python
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['/usr/lib/python2.7', ... ]
Second, ensure that there is a logging package. In my OS i have /usr/lib/python2.7/logging. I think you renamed the package accidentally; If so, rename it back.
I came across a very similar problem. The error I was receiving was: "AttributeError: ‘flask.logging’ object has no attribute ‘getLogger’". And the solution was downgrade the package Flask (settings -> project -> project interpreter).
Sorry, I solved it myself.
I thought Eclipse delete the .pyc files when I told it to clean the project, but it is not how it works apparently, So after 2 reinstalls of anaconda and configuration tweaks for this project (I have others ...), I finally remembered to check that ... the .pyc for the file was still there with the old name 'logging.pyc' ... thanks Eclipse as always, for wasting my time with your quirks!

Python3 on Ubuntu giving errors on help() command

I used help() in the python3 shell on Ubuntu 14.04
I got this output
Please help , don't know whats wrong.
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/_sitebuiltins.py", line 98, in __call__
import pydoc
File "/usr/lib/python3.4/pydoc.py", line 65, in <module>
import platform
File "/home/omega/platform.py", line 2, in <module>
print("System : ",platform.uname().system)
AttributeError: 'module' object has no attribute 'uname'
>>>
The problem is that platform is the name of a stdlib module, which help uses. By creating a module of your own with the same name that occurs before the stdlib in your sys.path, you're preventing Python from using the standard one.
The fact that your own platform module tries to use the stdlib module of the same name just compounds the problem. That isn't going to work; your import platform inside that module is just importing itself.
The solution is to not collide names like this. Look at the list of the standard modules, and don't create anything with the same name as any of them if you want to use features from that module, directly or indirectly.
In other words: Rename your platform.py to something else, or put it inside a package.
File "/home/omega/platform.py", line 2, in <module>
print("System : ",platform.uname().system)
This is the problem, go to platform.py and fix it, it will be ok. It says, platform has not any method called uname you probably misstyped.

Import Python module fails (http.cookies)

From what I've learned from my research here and elsewhere, it seems that if a) a module is located in the Python search path or b) contained in a package that is in the Python search path, that the import command should be able to find and import the module.
In the interactive script below, note that both of these conditions have been satisfied. the http folder contains an __init__.py file, making it a package, and that folder contains a module named cookies.py. Yet, the command import http.cookies fails, and the traceback looks like Python is searching for this module in the django folders, which I know will fail as there is no cookies.py module in the django http package folder. I also tried to manipulate the search path by editing my PYTHONPATH to ensure that the Standard Library http package folder is earlier in the search path, but as you can see below, the import is still failing.
What is causing this failure?
Python 3.3.1 (v3.3.1:d9893d13c628, Apr 6 2013, 20:25:12) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys
>>> for item in sys.path: print(item)
C:\Python33\Lib\idlelib
C:\Python33\lib\site-packages\setuptools-1.1.7-py3.3.egg
c:\Python33\Lib\http
C:\Python33\Lib\site-packages
C:\Python33\Lib\site-packages\django
C:\Python33\Lib\site-packages\django\bin
C:\Windows\system32\python33.zip
C:\Python33\DLLs
C:\Python33\lib
C:\Python33
C:\Python33\lib\site-packages\win32
C:\Python33\lib\site-packages\win32\lib
C:\Python33\lib\site-packages\Pythonwin
>>> import os
>>> os.path.isfile('C:/Python33/Lib/http/__init__.py')
True
>>> os.path.isfile('C:/Python33/Lib/http/cookies.py')
True
>>> import http.cookies
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
import http.cookies
File "C:\Python33\Lib\site-packages\django\http\__init__.py", line 1, in <module>
from django.http.cookie import SimpleCookie, parse_cookie
File "C:\Python33\Lib\site-packages\django\http\__init__.py", line 1, in <module>
from django.http.cookie import SimpleCookie, parse_cookie
File "C:\Python33\Lib\site-packages\django\http\cookie.py", line 5, in <module>
from django.utils.six.moves import http_cookies
File "C:\Python33\Lib\site-packages\django\utils\six.py", line 86, in __get__
result = self._resolve()
File "C:\Python33\Lib\site-packages\django\utils\six.py", line 105, in _resolve
return _import_module(self.mod)
File "C:\Python33\Lib\site-packages\django\utils\six.py", line 76, in _import_module
__import__(name)
ImportError: No module named 'http.cookies'
>>>
You added the Django top-level package to your sys.path:
C:\Python33\Lib\site-packages\django
Remove that entry, and don't add top-level packages to your path. Python finds the http top-level package in that directory first, so you are now effectively importing the django.http package, which does not have a cookies module.
You should only add the parent directory of a package to your path. C:\Python33\Lib\site-packages and C:\Python33\Lib are both already listed, so you do not need any of the following:
c:\Python33\Lib\http
C:\Python33\Lib\site-packages\django
C:\Python33\Lib\site-packages\django\bin
C:\Python33\lib\site-packages\win32
C:\Python33\lib\site-packages\win32\lib
C:\Python33\lib\site-packages\Pythonwin

Categories