将python脚本输出传递给另一个程序stdin

时间:2011-05-25 21:48:44

标签: python subprocess

我有一个应用程序从终端直接接收输入,或者我可以使用管道将另一个程序的输出传递给这个程序的stdin。我想要做的是使用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())

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

1 个答案:

答案 0 :(得分:3)

问题是appScan()只打印到stdout; 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())