I am doing the Python tutorial byte of python 120-1 pdf
Here are the instructions:
Start your choice of editor, enter the following program and save it
as helloworld.py
Example 3.2. Using a Source File
#!/usr/bin/python
# Filename : helloworld.py
print 'Hello World'
(Source file: code/helloworld.py) Run this program by opening a shell
(Linux terminal or DOS prompt) and entering the command python
helloworld.py. If you are using IDLE, use the menu Edit -> Run Script
or the keyboard shortcut Ctrl-F5. The output is as shown below.
Output
$ python helloworld.py
Hello World
I entered the program into text wrangler and saved it as helloworld.py
I then opened my terminal and entered python helloworld.py.
I received syntax error: invalid syntax
I then tried helloworld.py and also received syntax error: invalid syntax
Can anyone tell me where I went wrong?
You're using 2.x documentation, but are running 3.x. Either downgrade Python, or find more recent material.
#!/usr/bin/python
# Filename : helloworld.py
print('Hello World')
Related
I'm trying to learn Python and am trying to execute a python file in terminal. I'm using 2.7.3 python version on my OS X. I've changed the directory in terminal to where the file is located, but I'm getting an error in terminal:
>>> python ex1.py
File "<stdin>", line 1
python ex1.py
^
SyntaxError: invalid syntax
The ex1.py file contains:
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
Any ideas on how to fix this? Thx a bunch.
>>> python ex1.py
You are trying to run your script from within a python interpreter. You don't want to do that.
Instead, just run that command in a terminal, not in the interpreter
$ python ex1.py
If you are still in the interpreter, you can press ctrl+d to leave it and return to the 'normal' terminal
Exit python interpreter by typing exit() or press Crtl+Z
You will see the terminal now.
Type python file_name.py to run the code.
Happy coding!!!
Try type
exit()
return; then
python ex1.py
return
When I manually run this command in Terminal, it executes, but through Python it gives the error that the directory is not available in Python packages.
I am using the following command
source ~/trytry/shell.sh
This is my test shell file:
#!/bin/sh
echo hello
when I executed " source ~/test.sh ", it will print hello at console.
This is my python code:
>>> import commands
>>> commands.getstatusoutput("source ~/test.sh")
(0, 'hello')
It works without any problem. So, would you please show your code?
What it looks like to me is that you have a shell script, and not a python file which would have the .py extension instead of .sh. The error may have to do with the fact that it isn't a python file you're trying to run.
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.
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
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