【发布时间】:2014-05-21 13:03:15
【问题描述】:
我在一台运行 RH Linux 和 Python 2.6.6 的服务器上运行 python 脚本时遇到问题。当我运行任何脚本并产生异常时,脚本会挂起,直到我按下 CTRL-C,然后它会打印回溯信息。当我从命令行运行脚本而不直接调用 python,使用脚本第一行的 shebang 时,就会发生这种情况。如果我通过调用 python 执行脚本,我没有同样的挂起问题。我已经搜索并看到了类似的问题,但它们与所有 python 脚本都会发生这种情况的特定库有关。我用相同的脚本尝试了不同的服务器并且没有问题。我已经包含了一个我一直在测试的简单脚本。它试图打开一个不存在的文件。
#!/usr/bin/env python
tempfile = open('noexists.txt','r')
当我在命令行上以“test.py”的形式执行代码时,我得到以下响应:
~/bin$> test.py
^CTraceback (most recent call last):
File "/export/home/jwd3/bin/test.py", line 2, in <module>
tempfile = open('noexists.txt','r')
IOError: [Errno 2] No such file or directory: 'noexists.txt'
如果我将它作为“python test.py”执行,那么我会得到以下响应:
~/bin$> python test.py
Traceback (most recent call last):
File "test.py", line 2, in <module>
tempfile = open('noexists.txt','r')
IOError: [Errno 2] No such file or directory: 'noexists.txt'
这里的区别很难说,但是执行的时候就很明显了。查看第一个示例输出并注意 Traceback 之前的“^C”。在我按下 CTRL-C 之前,脚本只是挂起。第二个示例输出立即返回异常的回溯而不挂起。
我尝试将脚本移动到新位置,将 shebang 从 #!/usr/bin/python 更改为 #!/usr/bin/env python 和不同的脚本。在所有情况下,它们的行为都相同。任何帮助将不胜感激。我不想使用“python”格式调用所有 python 脚本。
【问题讨论】:
-
在命令行运行“which python”会得到什么输出?
-
如果你只是从命令行运行 python 然后插入你的命令“tempfile = open('noexists.txt','r')”你有什么?你能给我们你的python版本吗?你能列出(使用 ll)你当前的目录(从你运行脚本的地方)吗?
-
@RobWatts /usr/bin/python
-
@hzrari Python 2.6.6 (r266:84292, May 1 2012, 13:52:17) [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] 在 linux2 上输入“帮助” ”、“版权”、“学分”或“许可”以获取更多信息。 >>> tempfile = open('noexists.txt','r') Traceback(最近一次调用最后):文件“
”,第 1 行,在 IOError:[Errno 2] 没有这样的文件或目录: 'noexists.txt' >>> -
尝试过使用 strace 查看是什么阻碍了进程?
标签: python linux python-2.6