Run Python File In Python Shell or Directly - python

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?

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)

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!

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.

import urllib.request
with urllib.request.urlopen("http://www.yourwebsiteurl.com") as url:
htmltext = url.read()
print (htmltext)

Related

Running a Python script from the Python Shell

I wrote a script and saved it as test.py (code shown below). And when I run it from the script (Run Module 5), I get the result in the Python Shell.
But I have tried multiple suggestions available online to have it run from the Python Shell instead to which I fail (one error pasted below).
How can I run a python script from the python shell?
The version of Python I am running is 3.7.3 and in Windows.
#!/usr/bin/python3
print(" Hello, world!")
exec(open(test.py).read())
Output:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
exec(open(test.py).read())
NameError: name 'test' is not defined
You don't need the last line for it to run. All you need is:
!/usr/bin/python3
print(" Hello, world!")
If you want to run it from another file, don't use exec. Instead, import it.
import test
You need to pass the "test.py" as a string (use quotes).
test is not a known object.

Executing a python script from scala giving error while running the same script from the command line does NOT

This is my python script:
!/usr/bin/python
import sys
import magic
m=magic.from_file('<file with absolute path goes here>')
print(m)
On running this from the command line:
$ python script.py
Microsoft Word 2007+
results in the output of the TYPE of the document that file is. Using python-magic.
Now running the same script from scala using below code:
import sys.process._
def compWithLibmagic(){
val result = "python /script.py" !
}
throws the below error:
Traceback (most recent call last):
File "script.py", line 3, in <module>
import magic
ImportError: No module named magic
PS: I have both python 2.7 and python 3.6 installed on my machine and running the script using any of them from the command line runs just fine so I guess both of them are bundled with the MAGIC packages correctly.
Would highly appreciate any kind of help.
I will try to answer my own question in the best possible way.
While trying to execute the script.py from the command line using python compiler python2.7 was being used and when I tried to invoke the same script.py from the scala compiler using
import sys.process._
def compWithLibmagic(){
val result = "python /script.py" !
}
it was using python3 which was getting unnoticed. It took me a couple of days to actually figure this thing out and finally I removed all the python2.7 and python3 libraries and installed python 2.7 again and it worked like a charm.
It works from both python3 command and Scala code for me.
This should work.
import sys.process._
def compWithLibmagic(){
val result = "python3 script.py".!!
}

./xx.py: line 1: import: command not found

I am trying to use this Python urllib2 Basic Auth Problem bit of code to download a webpage content from an URL which requires authentication. The code I am trying is:
import urllib2, base64
request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
It's showing me:
./xx.py: line 1: import: command not found
./xx.py: line 3: syntax error near unexpected token `('
./xx.py: line 3: `request = urllib2.Request("http://api.foursquare.com/v1/user")'
I am wondering what I am doing wrong? I am using Python 2.7.5. How can I download file contents from an URL which requires authentication?
It's not an issue related to authentication at the first step. Your import is not working. So, try writing this on first line:
#!/usr/bin/python
and for the time being run using
python xx.py
For you here is one explanation:
>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>>
>>> print "%s" %xyz
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print "%s" %xyz
NameError: name 'xyz' is not defined
At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!
When you see "import: command not found" on the very first import, it is caused by the parser not using the character encoding matching your py file. Especially when you are not using ASCII encoding in your py file.
The way to get it right is to specify the correct encoding on top of your py file to match your file character encoding.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:
#!/usr/bin/python
Underneath which you would have the rest of the code (xx.py in your case) that you already have. Then run that same command at the terminal:
$ python xx.py
This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.
If you run a script directly e.g., ./xx.py and your script has no shebang such as #!/usr/bin/env python at the very top then your shell may execute it as a shell script. POSIX says:
If the execl() function fails due to an error equivalent to the
[ENOEXEC] error defined in the System Interfaces volume of
POSIX.1-2008, the shell shall execute a command equivalent to having a
shell invoked with the pathname resulting from the search as its first
operand, with any remaining arguments passed to the new shell, except
that the value of "$0" in the new shell may be set to the command
name. If the executable file is not a text file, the shell may bypass
this command execution. In this case, it shall write an error message,
and shall return an exit status of 126.
Note: you may get ENOEXEC if your text file has no shebang.
Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found.
Also, if you run your script as python xx.py then you do not need the shebang. You don't even need it to be executable (+x). Your script is interpreted by python in this case.
On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.
I've experienced the same problem and now I just found my solution to this issue.
#!/usr/bin/python
import sys
import os
os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))
This is the code[1] for my case. When I tried this script I received error message like :
import: command not found
I found people talks about the shebang. As you see there is the shebang in my python code above.
I tried these and those trials but didn't find a good solution.
I finally tried to type the shebang my self.
#!/usr/bin/python
and removed the copied one.
And my problem solved!!!
I copied the code from the internet[1].
And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.
I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)
Journeyer
PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.
[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy
It's about Shebang
#!usr/bin/python
This will tell which interpreter to wake up to run the code written in file.

install error or error running python file

I am running a basic Python file on Windows XP from IDLE.
The file name is assignment1.py.
The file content is:
import sys
var = 5
but when I run it, it gives the error:
Command: python assignment1.py
SyntaxError: invalid syntax
Then I tried another thing which also gave an error:
Command: which python
SyntaxError: invalid syntax
Not sure if the installation is wrong or something.
I am able to run the print command successfully:
>>> print "I am working fine"
I am working fine
Not sure of the issue. Request help.
It looks like what you are entering as the "command" is being interpreted as Python code. I mean, python assignment1.py is interpreted as Python code. The result is as expected:
$ python -c 'python assignment1.py'
File "<string>", line 1
python assignment1.py
^
SyntaxError: invalid syntax
You need to run the file in the correct way, probably via the IDLE menu or by pressing F5. You can check these questions for details:
How do I run a Python program?
Running Python script from IDLE on Windows 7 64 bit

Python+ubuntu error

Am trying to run the following python program
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
f=open('out.txt')
for a in f:
print regex.findall(a)
print '\n'
when I type the code into the interpreter manually, it works as expected
but when i save it as a file and try to run it , it gives errors.
The command i used to run it is
chmod +x
sudo ./pymod.py
ERROR:
./pymod.py: 2: Syntax error: "(" unexpected
if i dont use sudo, the error i get is
./pymod.py: line 2: syntax error near unexpected token `('
./pymod.py: line 2: `regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")'
am using ubuntu 10.04 with everything on default
it takes about 10-15 seconds for the error to appear
Your file should start with shebang. You should include the path to the python interpreter
#!/usr/bin/env python
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
Check out : http://en.wikipedia.org/wiki/Shebang_(Unix)
This is probably executing as a bash script instead of in Python. Put
#!/usr/bin/env python
at the beginning of your script.
When you set something as executable, you have to specify what you want it to run it with, or Linux will consider it to be a bash script.
Add this as the first line of the file:
#!/usr/bin/python
Or run it like:
python pymod.py
Cheers!
Either use the "shebang". I.e. put
#! /usr/bin/python
as the first line of your script.
Or teach your ubuntu how to treat python scripts without it
as described here: http://www.daniweb.com/code/snippet241988.html

Categories

Resources