Python 2.6:使用 Popen 从 bash 命令获取输入并作为变量进行通信和存储

Python 2.6: Get input from bash command with Popen and communicate and store as variable

我需要从 Bash 命令获取输入并将其存储为 Python 变量(价格;单个浮点数)。在 Python 2.7 上,以下工作正常:

bashCommand = "curl -s 'http://download.finance.yahoo.com/d/quotes.csv?s=vwrl.as&f=l1'"
sprice = float(subprocess.check_output(bashCommand, shell=True))

但是 Python 2.6 check_output 不可用。相反,我们必须使用:

proc = Popen(['curl', '-s', 'http://download.finance.yahoo.com/d/quotes.csv?s=vwrl.as&f=l1'], stdout=PIPE)
print (proc.communicate()[0].split())

它显示了我们之后的浮动,用方括号括起来。

['40.365']

如果我想看到输出并完成,那没关系。但是我需要 将它存储在一个 Python 变量中,就像在之前的 (2.7) 案例 中一样。但是,当我尝试将其分配给变量时,我得到:

Traceback (most recent call last):   
  File "arr.py", line 49, in <module>
    sprice = proc.communicate()[0].split()
  File "/usr/lib/python2.7/subprocess.py", line 791, in communicate
    stdout = _eintr_retry_call(self.stdout.read)
  File "/usr/lib/python2.7/subprocess.py", line 476, in _eintr_retry_call
    return func(*args)
ValueError: I/O operation on closed file

正确的做法是什么?

import commands
status, output = commands.getstatusoutput("curl -s http://download.finance.yahoo.com/d/quotes.csv?s=iwda.as&f=l1")

来自the docs

Execute the string cmd in a shell with os.popen() and return a 2-tuple (status, output). cmd is actually run as { cmd ; } 2>&1, so that the returned output will contain output or error messages.

我的语法错误。这个问答直截了当。

Subprocess Popen and PIPE in Python

所以命令是:

Popen(['curl', '-s', 'http://download.finance.yahoo.com/d/quotes.csv?s=vwrl.as&f=l1'], stdout=PIPE).communicate()[0]