Codest Codest - 4 months ago 8
Python Question

Executing modules as scripts

I am learn python now, and today, i met a problem
in
http://docs.python.org/release/2.5.4/tut/node8.html


6.1.1 Executing modules as scripts

When you run a Python module with

python fibo.py <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`
fib(int(sys.argv[1]))



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 fibo.py 50 1 1 2 3 5 8 13 21

34



but when i do this in shell, i got

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


how to execute script correctly?

fibo.py is

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


def fib2(n):
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result

if __name__ =="__main__":
import sys
fib(int(sys.argv[1]))

Answer

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.

edit:

I have figured out what is going wrong. You are trying to run python fibo.py 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 fibo.py 222
  File "<stdin>", line 1
    python fibo.py 222
              ^
SyntaxError: invalid syntax
>>>

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