【问题标题】:Python code that doesn't work from the command line不能从命令行运行的 Python 代码
【发布时间】:2011-04-16 22:59:35
【问题描述】:

我在 Python 2.6 中编写的模块 (test.py) 可以通过以下命令从 Python IDLE 导入并完美运行:

import test
test.run_test_suite()

但是,如果我在命令行中使用命令“python test.py”,它显然会在命令“import os”上崩溃(根据回溯)。

从下面的代码可以看出,当从命令行运行时,它的执行应该与在 IDLE 中运行时相同。为什么不在 IDLE 中运行它会导致问题?我的 google-foo 只能在代码在命令行运行但不能在 IDLE 中运行时得到结果。

if __name__ == "__main__":
    table = run_test_suite()
    print '---=== Results ===---'
    print_table(table)

需要指出的是,这个模块无非就是做大量的基础数学来检查一些外部计算的数据是否可行。

完整的追溯是:

Traceback (most recent call last):
  File "...\Python\test.py", line 170, in <module>
    print '---=== Results ===---'
  File "...\Python\test.py", line 160, in build_data
    if Links == False:
  File "...\Python\test.py", line 103, in load_table
    if Abbrev[M.solution_type()] == 'pos':
  File "...\Python\test.py", line 85, in build_example
    import os
  File "SnapPy.pyx", line 173, in snappy.SnapPy.uFatalError (SnapPy.c:5507)
snappy.SnapPy.SnapPeaFatalError: 
SnapPea crashed in function cusp_modulus(), defined in cusp_modulus.c.

【问题讨论】:

  • 如果它真的在import os 上崩溃,则表明您的python 路径有问题。请编辑您的帖子并包含回溯。
  • 如果你从命令行启动 python shell,然后在执行中导入你的文件,它是否工作?
  • @Eric,不,它也崩溃了。 @wok,没有文件访问权限,它自己构建示例数据。
  • @Jim,将“import math”或我能想到的任何其他模块添加到“import os”上面的行现在会导致它与“File”...\Python\test 一起崩溃。 py",第 85 行,在 build_example import math' 所以 import os 似乎不是真正的问题
  • import os 不会出现在您的回溯中。您的 snappy 安装似乎有问题。

标签: python debugging command-line python-idle


【解决方案1】:

你在这两种情况下都使用相同的 python 版本吗?从命令行启动时,您将获得路径中的第一个 Python,而 IDLE 很可能直接从快捷方式执行。
如果您的机器上安装了多个版本的 python,这可能会在两个完全不同的环境中转换。

【讨论】:

  • 不,我只安装了 python 2.6。
  • 如何在版本之间切换?
  • 在 Windows 上?您需要更改 .py 文件的文件关联,并更改路径。该任务可以自动执行,但我不知道是否有任何可用的操作(但从未搜索过)。
【解决方案2】:

在当前工作目录中查找名为 os.py 的文件。如果有,请重命名。或者查看 Python 文档中的“绝对导入”。

【讨论】:

  • 正如我在上面添加的那样,将“import math”或我能想到的任何其他模块添加到“import os”上面的行现在会导致它因“File”而崩溃...\Python\ test.py",第 85 行,在 build_example import math' 所以 import os 似乎不是一个真正的问题。工作目录中没有其他python文件。
猜你喜欢
  • 2010-10-29
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多