2011-05-25 70 views
2

我有一个应用程序直接从终端获取输入,或者我可以使用管道将另一个程序的输出传递到这个输入。我想要做的是使用python生成输出,所以它的格式正确,并通过相同的脚本传递给这个程序的标准输入。下面是代码:将python脚本输出传递给另一个程序stdin

#!/usr/bin/python 
import os 
import subprocess 
import plistlib 
import sys 

def appScan(): 
    os.system("system_profiler -xml SPApplicationsDataType > apps.xml") 
    appList = plistlib.readPlist("apps.xml") 
    sys.stdout.write("Mac_App_List\n" 
    "Delimiters=\"^\"\n" 
    "string50 string50\n" 
    "Name^Version\n") 
    appDict = appList[0]['_items'] 
    for x in appDict: 
     if 'version' in x: 
      print x['_name'] + "^" + x['version'] + "^" 
     else: 
      print x['_name'] + "^" + "no version found" + "^" 
proc = subprocess.Popen(["/opt/altiris/notification/inventory/lib/helpers/aex-  sendcustominv","-t","-"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE) 
proc.communicate(input=appScan()) 

出于某种原因,这个子我打电话不喜欢的是进入标准输入。但是,如果我删除了子进程项并只是将脚本打印到stdout然后从终端调用脚本(python appScan.py | aex-sendcustominv),则aex-sendcustominv能够接受输入。有没有办法在python中获取函数输出并将其发送到子进程的stdin?

+0

有一个类似的问题SO这里 - http://stackoverflow.com/questions/163542/python-how-do-i-pass-a-string -into-subprocess-popen-using-stdin-argument – 2011-05-25 22:03:39

回答

3

问题是appScan()只打印到标准输出; appScan()返回None,所以proc.communicate(input=appScan())相当于proc.communicate(input=None)。你需要appScan来返回一个字符串。

尝试此(未测试):

def appScan(): 
    os.system("system_profiler -xml SPApplicationsDataType > apps.xml") 
    appList = plistlib.readPlist("apps.xml") 
    output_str = 'Delimiters="^"\nstring50 string50\nName^Version\n' 
    appDict = appList[0]['_items'] 
    for x in appDict: 
     if 'version' in x: 
      output_str = output_str + x['_name'] + "^" + x['version'] + "^" 
     else: 
      output_str = output_str + x['_name'] + "^" + "no version found" + "^" 
    return output_str 

proc = subprocess.Popen(["/opt/altiris/notification/inventory/lib/helpers/aex-  sendcustominv","-t","-"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE) 
proc.communicate(input=appScan()) 
+0

哎呀,你完全正确,像魅力一样工作。 – Dishwishy 2011-05-26 00:54:33

相关问题