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