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

问题描述

| 我有一个应用程序,它可以直接从终端获取输入,也可以使用管道将另一个程序的输出传递到该程序的stdin中。我想做的是使用python生成输出,以便正确设置其格式,并将其从同一脚本传递到该程序的标准输入。这是代码
#!/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?     

解决方法

问题在于ѭ1仅打印到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())