Reputation: 213
I am just a beginner in Python. I created a file called as cc.py
and saved in the following path :
C:/Python33/cc.py
.
I am trying to run this file but nothing is happening.
In the python shell I am typing Python cc.py
but I am getting the following error:
SyntaxError: invalid syntax
I tried an alternative :
>>> execfile('cc.py');
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
execfile('cc.py');
NameError: name 'execfile' is not defined
The file contains the following lines of code :
import urllib
htmlfile = urllib.urlopen("http://google.com")
htmltext = htmlfile.read()
print htmltext
How should I run this file? I am totally confused. Can someone help me out?
Upvotes: 2
Views: 9811
Reputation: 1
import urllib.request
with urllib.request.urlopen("http://www.yourwebsiteurl.com") as url:
htmltext = url.read()
print (htmltext)
Upvotes: 0
Reputation: 385800
You wrote:
In the python shell I am typing Python cc.py but I am getting the following error:
SyntaxError: invalid syntax
If you want to run the python script, don't do it from the python shell. The "python" (not "Python") command needs to be run from a command prompt (DOS shell, terminal window, etc).
From a command prompt you should issue the command:
$ python cc.py
For a more complete description of the problem and solution, see Executing Scripts in the windows section of the python user guide, and also How do I run a python program under windows in the frequently asked question section of the python users guide.
Upvotes: 1
Reputation: 28232
In python 3, execfile
no longer exists. You can open it and execute it manually:
def xfile(afile, globalz=None, localz=None):
with open(afile, "r") as fh:
exec(fh.read(), globalz, localz)
And to execute:
>>> xfile(r'C:\path\to\file\script.py')
Credit to: What is an alternative to execfile in Python 3?
That's how you execute files from the interpreter.
Another way, you can execute it from the command prompt. Just open it and type:
$ cd filepath
$ python file.py
About the script you're running, there's also a confusion. Whatever example you are following, it's a Python 2 example, yet you are using Python 3. Change the request line to this:
htmlfile = urllib.request.urlopen("http://google.com")
Hope this helps!
Upvotes: 1
Reputation: 4079
print htmltext
should be print(htmltext)
. Also, execfile()
was removed from Python 3. It seems you are using a Python 2 book but running Python 3. These different versions of Python are incompatible, stick to one. For choosing which version, see this question.
An implemention of execfile()
:
def execfile(filename, *args, **kwargs):
with open(filename) as fp:
exec(fp.read(), *args, **kwargs)
Upvotes: 1