【问题标题】:Python Popen stdin PIPE gets spamedPython Popen stdin PIPE 被垃圾邮件
【发布时间】:2013-06-04 02:14:21
【问题描述】:

我有两个简单的程序:

test.sh

rm ~/out.txt
for ((i=0; i<10; i++)); do
  read j
  echo "read: '$j'" >> ~/out.txt
done

还有test.py

import sub
process
proc = subprocess.Popen('/Users/plg/test.sh', stdin=subprocess.PIPE)
proc.stdin.write('1\n')
proc.stdin.write('2\n')

当我运行 test.py(使用 Python 2.7.2)时,~/out.txt 包含以下内容:

read: '1'
read: '2'
read: ''
read: ''
read: ''
...

为什么 test.sh 会收到最后 8 行?它应该卡住并等待输入。 但显然,一旦我写了一些东西并且 Python 退出,Popen 就会发送垃圾邮件“\n”。

我找不到解决方法,使用 proc.stdin.flush() 和 proc.stdin.close() 没有任何好处。如何防止这种情况发生?

【问题讨论】:

    标签: python stdin popen


    【解决方案1】:
    import subprocess
    proc = subprocess.Popen('/Users/plg/test.sh', stdin=subprocess.PIPE)
    proc.stdin.write('1\n')
    proc.stdin.write('2\n')
    proc.wait()
    

    【讨论】:

    • 谢谢,我使用了这个(在示例中,读取需要超时,否则 Python 将永远等待)。
    【解决方案2】:

    Popen 不会向任何输出发送垃圾邮件,当您的 Python 程序退出时 test.sh 将收到一个 EOF(文件结尾),指示没有任何内容可读取,此时 test.sh 中的 read 命令每次调用都会给出一个空字符串,并给出退出状态码 1。

    在永远不会发生的输入上设置 test.sh 块实际上没有任何意义,您最好检查read 的状态代码并在遇到 EOF 或其他读取错误时退出:

    rm ~/out.txt
    for ((i=0; i<10; i++)); do
      read j
      if [ $? != 0 ]; then
        break
      fi
      echo "read: '$j'" >> ~/out.txt
    done
    

    【讨论】:

    • 哦,现在我明白了!这就像从一个空文件中读取。谢谢!
    • 感谢您使用新代码进行编辑,但我正处于与外部程序(java 应用程序)交互的情况,我不能只修改源代码才能工作就像我需要的那样,我必须适应。
    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2012-05-13
    相关资源
    最近更新 更多