【问题标题】:Script doesn't want to run from python shell脚本不想从 python shell 运行
【发布时间】:2013-08-03 14:19:58
【问题描述】:

我打开 C:\Python27\python.exe,输入 clean_index.py(这是一个位于 C:\Python27 中的文件),然后得到:

>>> clean_index.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'clean_index' is not defined

这是怎么回事? 我输入 C:\Python27\clean_index.py,同样的。

【问题讨论】:

    标签: python python-2.7 command-line


    【解决方案1】:

    使用execfile:

    >>>execfile('clean_index.py')
    

    或者直接运行它(不在 python shell 中):

    $ python clean_index.py
    

    假设您的路径中有python

    或者,在 python shell 中使用import

    >>>import fibo
    >>>fibo.fib(1000)
    1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
    

    模块导入示例取自 the docs。文件名为fibo.py

    由于您可能只是想运行该文件,我建议您使用 second 选项。

    【讨论】:

    • 我认为重要的是要澄清当你说“直接运行”时,你的意思是从你的普通终端 shell(bash、命令提示符等),而不是交互式 python shell。
    • @SethMMorton 是的,我用&gt;&gt;&gt; 表明你在python 提示符中,但这是一个很好的观点,有点不清楚
    • 是的,&gt;&gt;&gt; 很明显它是 Python 提示符,但是对于其他提示符,您可以使用 $#&gt;... 有太多可供选择!我只是认为,由于 OP 认为您可以将 Python 提示符用作一般命令行提示符,因此如果不明确说明在普通 shell 中运行 python clean_index.py,他们可能不清楚该怎么做。
    最近更新 更多