【发布时间】:2012-10-29 15:19:37
【问题描述】:
我在使用 Python 2.5.2 时注意到以下情况(使用 2.7 时不会出现):
#!/usr/bin/python
import sys
for line in sys.stdin:
print line,
输出:
$ echo -e "one\ntwo\nthree" | python test.py
$ one
$ two
$ three
正如预期的那样。但是,如果我将 subprocess 导入此脚本:
#!/usr/bin/python
import sys
import subprocess
for line in sys.stdin:
print line,
输出:
$ echo -e "one\ntwo\nthree" | python test.py
$ two
$ three
输出的第一行发生了什么?
更新:
我想我可能已经找到了问题的根源。我的cwd 中有一个名为time.py 的文件。每次我运行导入了subprocess 的脚本时,都会创建一个time.pyc,这表明./time.py 也正在被导入。如果我删除.pyc 和time.py 文件,脚本运行正常;但是,仍然存在一个问题,为什么 subprocess 导入会导致 ./time.py 也被导入?
我已将其进一步缩小到 time.py 中导致奇怪行为的确切行。我已将工作目录和文件内容剥离为影响输出的内容:
test.py
#!/usr/bin/python
import sys
import subprocess
for line in sys.stdin:
print line,
time.py
#!/usr/bin/python
import sys
for line in sys.stdin:
hour = re.search(r'\b([0-9]{2}):', line).group(1)
使用任何类型的输入运行 test.py 会导致第一行输出被省略并创建 time.pyc。
【问题讨论】:
-
我无法在 2.4.3 上确认: "echo -e "one\ntwo\nthree" | python test.py" 导致最后一个示例为 "-e 一二三"。
-
@tb-:您必须使用 bash shell。 echo 是内置的,并且 tcsh (例如)不支持 -e 标志。
-
嗯,我实际上根本无法确认这一点:Ubuntu 上的 python2.5.6
-
@sharth 用 bash,结果是一样的(没有 -e)
-
@SilentGhost:我在 Debian 5.0.6 上使用 2.5.2 得到了这些结果。同一台机器上的 Python 2.6.6 和 2.7.1 的行为符合预期。
标签: python python-import python-2.5