Python's exec running in module works but in function not - python-3.x

This works:
import os
import sys
with open('tests.py') as fptr:
script_content = fptr.read()
exec(script_content)
And this not:
def run():
import os
import sys
with open('tests.py') as fptr:
script_content = fptr.read()
exec(script_content)
run()
Result:
Traceback (most recent call last):
File "tmp.py", line 8, in <module>
run()
File "tmp.py", line 6, in run
exec(script_content)
File "<string>", line 15, in <module>
File "<string>", line 16, in PlaceSpitter
NameError: name 'Place' is not defined
Could anyone tell my why and how to fix it?

I've read again - carrefully - python's docs especially this one:
Remember that at module level, globals and locals are the same dictionary
And try this:
def run():
import os
import sys
with open('tests.py') as fptr:
script_content = fptr.read()
exec(script_content, globals())
run()
which now works!
I still don't know why but now at least it works.

Related

Can't import urllib.request module in python 3

I was executing a code from the book Think Python in Python 3. The code follows.
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import urllib.request
conn = urllib.request.urlopen('http://thinkpython.com/secret.html')
for line in conn:
print(line.strip())
When I execute this code in my machine's terminal, I got this following output.
Traceback (most recent call last):
File "secret.py", line 4, in <module>
import urllib.request
File "/usr/lib/python3.6/urllib/request.py", line 84, in <module>
import base64
File "/usr/lib/python3.6/base64.py", line 10, in <module>
import struct
File "/usr/lib/python3.6/struct.py", line 13, in <module>
from _struct import *
ModuleNotFoundError: No module named '_struct'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 12, in <module>
import subprocess, tempfile, os.path, re, pwd, grp, os, time
File "/usr/lib/python3.6/subprocess.py", line 136, in <module>
import _posixsubprocess
ModuleNotFoundError: No module named '_posixsubprocess'
Original exception was:
Traceback (most recent call last):
File "secret.py", line 4, in <module>
import urllib.request
File "/usr/lib/python3.6/urllib/request.py", line 84, in <module>
import base64
File "/usr/lib/python3.6/base64.py", line 10, in <module>
import struct
File "/usr/lib/python3.6/struct.py", line 13, in <module>
from _struct import *
ModuleNotFoundError: No module named '_struct'
I did this same code in Anaconda, and I got the correct output. Can anybody help me with this problem.

AttributeError: module 'typing' has no attribute 're' in pandas Python 3.7

I can't import pd from pandas because i have this error. I search on google but I didn't find the fix for this..
>>> import pandas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python37\lib\site-packages\pandas\__init__.py", line 23, in <module>
from pandas.compat.numpy import *
File "C:\Python37\lib\site-packages\pandas\compat\__init__.py", line 431, in <module>
re_type = typing.re.Pattern
AttributeError: module 'typing' has no attribute 're'
I think this is changing underneath us as Python's typing module matures, but in our case, the issue was that we did from Typing import re, and then later did something like:
def funct(some_re: re.Pattern):
The fix was dumb. Simply change your import to be from typing import Pattern and then do:
def funct(some_re: Pattern):
Bleh. Warts.

When I try to run Python script on any editor or cmd I get this error

on editor Sublime Text 3, visual studio code, notepad++ or cmd the same problem
C:\Users\Egypt>python Desktop/python/any file.py
when i try run any file i get this
Traceback (most recent call last):
File "Desktop/python/reqweb.py", line 1, in <module>
from selenium import webdriver
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\__init__.py", line 18, in <module>
from .firefox.webdriver import WebDriver as Firefox # noqa
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 28, in <module>
import shutil
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 22, in <module>
import bz2
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\bz2.py", line 18, in <module>
from threading import RLock
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\threading.py", line 7, in <module>
from traceback import format_exc as _format_exc
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\traceback.py", line 5, in <module>
import linecache
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\linecache.py", line 11, in <module>
import tokenize
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\tokenize.py", line 34, in <module>
from token import *
File "C:\Users\Egypt\Desktop\python\token.py", line 1, in <module>
import facebook
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\site-packages\facebook\__init__.py", line 30, in <module>
import requests
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\__init__.py", line 43, in <module>
import urllib3
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\site-packages\urllib3\__init__.py", line 8, in <module>
from .connectionpool import (
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\site-packages\urllib3\connectionpool.py", line 3, in <module>
import logging
File "C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\logging\__init__.py", line 207, in <module>
_lock = threading.RLock()
AttributeError: module 'threading' has no attribute 'RLock'
please help i try uninstall python and reinstall But the same problem
this error Appears only in scripts inside import models
I realize the comment above more or less resolved the issue, but to explain what was actually happening (because I just had a very similar problem and found this question):
It looks like your file C:\Users\Egypt\Desktop\python\token.py was incorrectly being picked as the source for the from token import * statement in the system's C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\tokenize.py module. It was actually intending to reference the module C:\Users\Egypt\AppData\Local\Programs\Python\Python35\lib\token.py. Since your version of the file wasn't what it expected, it raised an exception.
Either of these fixes should work in this case:
Rename your token.py file to a non-conflicting name
Don't execute python from this folder as the current directory.

ImportError: cannot import name 'errors'

Using sockjs with Tornado. On server run, this is the trace returned :
python server.py
Traceback (most recent call last):
File "server.py", line 10, in <module>
from sockjs.tornado import SockJSRouter
File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/__init__.py", line 20, in <module>
from sockjs.route import get_manager, add_endpoint
File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/route.py", line 11, in <module>
from sockjs.transports import handlers
File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/transports/__init__.py", line 3, in <module>
from .jsonp import JSONPolling
File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/transports/jsonp.py", line 8, in <module>
from .base import StreamingTransport
File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/transports/base.py", line 2, in <module>
from aiohttp import errors
ImportError: cannot import name 'errors'
I would recommend you to upgrade python version to
Python 3.5+ and utilize PEP-492 aka async/await. If you are using Python 3.4 please replace await with yield from and async def with #coroutine e.g.:
async def coro(...):
ret = await f()
should be replaced by:
#asyncio.coroutine
def coro(...):
ret = yield from f()
from aiohttp documentaion:
Dependencies
Python 3.4.2+
chardet, multidict, async_timeout, yarl
Optionally you may install the cChardet and aiodns libraries (highly recommended for sake of speed).
$ pip install cchardet
$ pip install aiodns

Cython with Numpy / AttributeError: 'module' object has no attribute 'Handler'

I want to use Numpy in Cython, but encountered the following error. This error happens even if I run the simple code, so it should be an issue related to importing Numpy.
My environment:
OS X Yosemite
Python 3.4.3
setup.py:
import numpy as np
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'my_code',
ext_modules = cythonize('my_code.pyx'),
include_path = [numpy.get_include()]
)
my_code.pyx:
cimport numpy as np
cdef int a
Execute in Terminal:
$ python3 setup.py build_ext --inplace
Traceback (most recent call last):
File "/Users/***/setup.py", line 1, in <module>
import numpy as np
File "/usr/local/lib/python3.4/site-packages/numpy/__init__.py", line 180, in <module>
from . import add_newdocs
File "/usr/local/lib/python3.4/site-packages/numpy/add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc
File "/usr/local/lib/python3.4/site-packages/numpy/lib/__init__.py", line 8, in <module>
from .type_check import *
File "/usr/local/lib/python3.4/site-packages/numpy/lib/type_check.py", line 11, in <module>
import numpy.core.numeric as _nx
File "/usr/local/lib/python3.4/site-packages/numpy/core/__init__.py", line 58, in <module>
from numpy.testing import Tester
File "/usr/local/lib/python3.4/site-packages/numpy/testing/__init__.py", line 10, in <module>
from unittest import TestCase
File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/__init__.py", line 59, in <module>
from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf,
File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 253, in <module>
class _CapturingHandler(logging.Handler):
AttributeError: 'module' object has no attribute 'Handler'
Old question but I ran into this because I had a very similar issue with numpy.
It turns out I had a directory named logging as a sibling of the script I was trying to run. So the problem was a simple naming collision between my local project folder and the logging module numpy expected to find. Renaming the project logging folder solved the issue for me.
Looking at OP's error message, I suspect this was the case for them as well.

Resources