I am learning Python, and I have written a script per an example in the book I am reading where it imports the urllib library. This works fine when I run it from IDLE, but if I go to the folder where the file is and run “python test.py” I get an error where it tells me that
Traceback (most recent call last):
File "test.py", line 1, in ?
import urllib.request
ImportError: No module named request
I verified that I am using Python 3.1.2. Any suggestions or ideas why this fails on the command line?
My code:
import urllib.request
import time
price = 99.99
while price > 1.01:
time.sleep(3)
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
print ("Buy!")
urllib.requestwas introduced with Python 3. It is very possible that when you run the code from the command line, you are using an older, Python 2.x binary.Type
python --versionon the command line to see which Python is being used.Edit in response to Drewdin’s comment
Running the Python 3.1.2 installer for Mac OS X, I see this:
So depending on how you installed it, you may already have links placed in
/usr/local/bin, which will be in your path. If you chose this option at install time, all you should have to do is typepython3orpython3.1in your shell to get the updated version.Otherwise, either double click that “Update Shell Profile”, or add this to your path:
export PATH=$PATH:/Library/Frameworks/Python.framework/Versions/3.1/binBy default, Python 3.x does not make the
pythoncommand alias in Unix/Linux environments because it could possibly interfere with system processes/commands dependent on the default-installed Python.