关于python:将模块作为脚本执行

Executing modules as scripts

我现在在学Python,今天遇到了一个问题在里面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

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:

1
2
3
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

但当我在贝壳里做这个的时候,我

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

如何正确执行脚本?

FiBo.Py是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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]))


你到底做了什么?您运行的代码是什么?

听起来你在脚本中犯了一个错误——可能是冒号丢失或缩进错误。如果看不到正在运行的文件,就不可能说更多。

编辑:

我已经知道出了什么问题。您试图在python shell中运行python fibo.py 222。当我这样做时,我会得到同样的错误:

1
2
3
4
5
6
7
8
9
10
[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
>>>

您需要从操作系统的命令行提示符运行它,而不是从Python的交互式shell中运行它。

确保首先更改为python主目录。例如,在操作系统的命令行中,根据您的Python版本,键入:cd c:python33--我的是3.3。然后键入:python fibo.py 200(例如)