Codest Codest - 1 year ago 93
Python Question

Executing modules as scripts

I am learn python now, and today, i met a problem

6.1.1 Executing modules as scripts

When you run a Python module with

python <arguments>

the code in the module will be executed, just as if you imported it, but with the
__name__ set to "__main__". That means that by adding this code at the end of
your module:

if __name__ == "__main__":
import sys`

you can make the file usable as a script as well as
an importable module, because the code
that parses the command line only runs
if the module is executed as the
"main" file:

$ python 50 1 1 2 3 5 8 13 21


but when i do this in shell, i got

File "<input>", line 1
python 222
SyntaxError: invalid syntax

how to execute script correctly? is

def fib(n):
while b<n:
print b,
a,b = b,a+b

def fib2(n):
while b<n:
return result

if __name__ =="__main__":
import sys

Answer Source

What exactly did you do in the shell? What is the code you are running?

It sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more.


I have figured out what is going wrong. You are trying to run python 222 in the python shell. I get the same error when I do that:

[138] % python
Python 2.6.1 (r261:67515, Apr  9 2009, 17:53:24)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> python 222
  File "<stdin>", line 1
    python 222
SyntaxError: invalid syntax

You need to run it from the operating system's command line prompt NOT from within Python's interactive shell.