python 3 import urllib.request module - python-3.x

I am learning to grab pictures from URL and found a Q&A here. Since it's Python 3, I changed import urllib to import urllib.request and
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
to
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg").
It doesn't work! It says AttributeError: 'module' object has no attribute 'urlretrieve'
I then changed urllib.urlretrieve to def request.urlretrieve and got SyntaxError: invalid syntax
I also tried def urlretrieve and it's not working either.
Could anyone tell me how to get it right? Thanks!
What if the URL contains more than one pic?

You need to use:
from urllib import request
request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
You can use also use:
import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

Since you have imported urllib.request module, doesn't it seem obvious that you should call its method urlretrieve(args) as urllib.request.urlretrieve(args).
When you type import <module>, you call its method using <module>.method(args) (As specified in above code).
Alternatively, you can import the module using from <module> import * and then call its method using method(args). Eg -
from urllib.request import *
urlretrieve(args).
Another way is to only import the method you need to use in your program using
from <module> import method and then call the method using method(args). Eg -
from urllib.request import urlretrieve and then call the method using
urlretrieve(args).
The urllib.request module for Python 3 is well documented here.

Related

ModuleNotFoundError: No module named 'google.cloud.automl_v1beta1.proto'

I am trying to follow this tutorial on Google Cloud Platform,
https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/notebooks/samples/tables/census_income_prediction/getting_started_notebook.ipynb, however, I am running into issues when I try to import the autoML module, specifically the below two lines
# AutoML library.
from google.cloud import automl_v1beta1 as automl
import google.cloud.automl_v1beta1.proto.data_types_pb2 as data_types
The first line works, but for the 2nd one, I get the error: ModuleNotFoundError: No module named 'google.cloud.automl_v1beta1.proto'. It seems for some reason there is no module called proto and I cannot figure out how to resolve this. There are a couple of posts regarding the issue of not being able to find module google.cloud. In my case I am able to import automl_v1beta1 from google.cloud but not proto.data_types_pb2 from google.cloud.automl_v1beta1
I think you can:
from google.cloud import automl_v1beta1 as automl
import google.cloud.automl_v1beta1.types as data_types
Or:
import google.cloud.automl_v1beta1 as automl
import google.cloud.automl_v1beta1.types as data_types
But (!) given the import errors, there may be other changes to the SDK in the code that follows.

How to suppress outputs from specific modules and hidden class methods in Python?

This is how the code looks like
#!/usr/bin/env python3
#encoding:utf-8
import requests, numpy, fasttext, os, sys
from itertools import product
from math import sqrt
en_model=fasttext.load_model(path='crawl-300d-2M-subword.bin')
The script is intended to train a classification model using some NLP techniques. Here is the problem.
The last line of the snippet, for some unknown reason, outputs an empty line to the stderr, even though it runs without error. Is there any way to suppress it from the calling module, or do I have to hack into the fasttext module to know which line is causing this? In general, is there any way to suppress any stdout or stderr echo within a code snippet, specifically when I know that they are caused by modules being imported rather than what I wrote?
You can check contextlib.redirect_stdout and contextlib.redirect_stderr
Sample:
from contextlib import redirect_stdout
from contextlib import redirect_stderr
import os
def cache_stdouterr(func):
def wrapper():
with open(os.devnull,"w") as f:
with redirect_stdout(f):
with redirect_stderr(f):
func()
return wrapper
#cache_stdouterr
def noprint():
print("notprinted")
def toprint():
print("shouldbeprinted")
toprint()
noprint()
# python3 test_redirect.py
shouldbeprinted
This is the generic solution. For your specific problem , you can try this :
#!/usr/bin/env python3
#encoding:utf-8
import requests, numpy, fasttext, os, sys
from contextlib import redirect_stdout, redirect_stderr
from itertools import product
from math import sqrt
with redirect_stderr(open(os.devnull,"w")):
en_model=fasttext.load_model(path='crawl-300d-2M-subword.bin')

Why does unittest.mock.patch work with testfixtures?

Why doesn't accessing unittest.mock.patch throw an attribute error when I import testfixtures in the below code?
I myself suspect that it is because testfixtures might be importing unittest.mock somewhere internally however, is there any way I could change this behavior if I want unittest.mock to always be imported explicitly and get an AttributeError otherwise?
import unittest
import sys
import os
import testfixtures
class Test(unittest.TestCase):
#unittest.mock.patch('sys.version_info', (2,7,0))
def test_version(self):
assert(sys.version_info < (3,0,0))
Accessing unitest.mock without importing it should throw an AttributeError but that's not the case when testfixtures is imported.

i am trying to take shot from ipcamera and open as opencv and convert to numpy formate

use IP Webcam with opencv as a wireless camera
i fallowed this steps
https://thecodacus.com/ip-webcam-opencv-wireless-camera/#.Ws-oS53hXVM
But i need for python3
i tried my best to do
here my code
import urllib.request
import cv2
import numpy as np
url='http://192.168.43.1:8080/shot.jpg'
while True:
x=urllib.request.urlopen(url)
imgNp=np.array(bytearray(x.read()),dtype=np.uint8)
img=cv2.imdecode(imgNp,-1)
cv2.imshow('test',img)
if ord('q')==cv2.waitKey(10):
exit(0)
But it gives error message
File "ipcam.py", line 8
x=urllib.request.urlopen(url)
^
IndentationError: expected an indented block
I am not Good at python3 help me please
Python Is Sensitive To Indentation..
Its equivalent to {} in C, C++, etc, Think of it as a block of codes to be executed..
import urllib.request
import cv2
import numpy as np
url='http://192.168.43.1:8080/shot.jpg'
while True:
x=urllib.request.urlopen(url)
imgNp=np.array(bytearray(x.read()),dtype=np.uint8)
img=cv2.imdecode(imgNp,-1)
cv2.imshow('test',img)
if ord('q')==cv2.waitKey(10):
exit(0)

Python global variable with no import or global declaration

I'm trying to add a couple of miscellaneous development helpers to my python project in such a way that I don't need to either import them or declare them global at the call site, just to save myself some typing.
Example usage would be something like:
# Somewhere, maybe src/__init__.py?
from pprint import pprint
superduperglobaleasyusenamespace.p = pprint
# A different file somewhere in my project
def whatever():
p('hello')
I looked at builtin but wasn't able to get it to work. If that's the correct solution, provide example code that works in python3.
Add this as very first line in your program:
__builtins__.p = pprint
In general, it is not recommend to modify the builtin name space. An import is just one line after all.
Example
# mod1.py
from pprint import pprint
__builtins__.p = pprint
import mod2
and
# mod2.p
print(p)
Now:
python mod1.py
<function pprint at 0x10df28e18>

Resources