我有一个应用程序直接从终端获取输入,或者我可以使用管道将另一个程序的输出传递到这个输入。我想要做的是使用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?
有一个类似的问题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