Python2.6:使用Popen从bash命令获取输入,并将其作为variab进行通信和存储

2024-04-26 06:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从Bash命令获取输入并将其存储为Python变量(sprice;单个float)。在Python2.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))

但是,在python2.6上,check_输出不可用。相反,我们必须使用:

^{pr2}$

它显示了我们要的浮动,用括号括起来。在

['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

什么是正确的方法?


Tags: inpylibusrcheckstdoutlinecall
2条回答
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]

相关问题 更多 >