将模块作为脚本执行

pri*_*e23 7 python windows

我现在正在学习python,今天,我在http://docs.python.org/release/2.5.4/tut/node8.html遇到了一个问题.

6.1.1将模块作为脚本执行

当你运行Python模块时

python fibo.py <arguments>

模块中的代码将被执行,就像您导入它一样,但__ ____设置为"__main__".这意味着通过在模块的末尾添加此代码:

if __name__ == "__main__":
    import sys`
    fib(int(sys.argv[1]))
Run Code Online (Sandbox Code Playgroud)

您可以使该文件可用作脚本以及可导入模块,因为解析命令行的代码仅在模块作为"主"文件执行时才会运行:

$ python fibo.py 50 1 1 2 3 5 8 13 21 34

但是当我在shell中这样做时,我得到了

File "<input>", line 1
python fibo.py 222
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

如何正确执行脚本?

fibo.py是

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]))
Run Code Online (Sandbox Code Playgroud)

Dav*_*rby 13

你究竟在shell中做了什么?你运行的代码是什么?

听起来你在你的脚本中犯了一个错误 - 可能错过了冒号或者缩进了缩进.如果没有看到你正在运行的文件,就不可能多说.

编辑:

我弄清楚出了什么问题.您正在尝试python fibo.py 222python shell中运行.当我这样做时,我得到同样的错误:

[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
>>>
Run Code Online (Sandbox Code Playgroud)

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

确保首先更改为Python主目录.例如,从操作系统的命令行输入:cd C:\ Python33\ - 取决于您的python版本.我的是3.3.然后键入:python fibo.py 200(例如)