【问题标题】:Pass python script output to another programs stdin将 python 脚本输出传递给另一个程序标准输入
【发布时间】:2011-09-02 03:35:22
【问题描述】:

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

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

【问题讨论】:

标签: python subprocess


【解决方案1】:

问题是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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多