python - 将模块作为脚本执行

标签 python windows

我现在在学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 <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

但是当我在 shell 中执行此操作时,我得到了

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

如何正确执行脚本?

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]))

最佳答案

你在 shell 中到底做了什么?您正在运行的代码是什么?

听起来您在脚本中犯了一个错误 - 可能缺少冒号或缩进错误。没有看到您正在运行的文件,就不可能说更多。

编辑:

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

[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 主目录。例如,从操作系统的命令行键入:cd C:\Python33\——取决于您的 python 版本。我的是3.3。然后输入:python fibo.py 200(例如)

关于python - 将模块作为脚本执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636798/

相关文章:

python - 当 spss.Submit() 内的 spss 命令会创建警告时,SPSS-Python 脚本会停止并出现错误

python - 有没有办法增加分配给jupyter笔记本的内存

c++ - VC++2008中存在图像控件

windows - 线程排序服务场景

Python:如何以编程方式更新属性?

python - ImportError : libpng16. so.16: 无法打开共享对象文件: 没有那个文件或目录

python - 0 是 0 == 0(#evaluates 为真?)

Windows 批处理 : Can't echo ASCII art with . _|_

windows - .bat 文件中的 Sed 等价物

windows - 怎么能在网上看到文件版本却不能下载呢?