Python Capture reply from powershell

限于喜欢 提交于 2019-12-31 05:15:12

问题


The code below works when typed manually however when I run the program.py nothing prints. My ultimate goal is to retrieve this data from user pc to create an easy way to recreate shortcuts.... My users somehow lose them lol

import smtplib, os, subprocess, sys
from string import ascii_uppercase
from cStringIO import StringIO

data = os.popen(r"dir %userprofile%\desktop\*.lnk* /s/b").read()
file = open("testitem.txt", "w")
file.write(data)
file.close()


my_data = dict(zip(ascii_uppercase,open("testitem.txt")))


old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

for key, value in my_data.iteritems():
    subprocess.Popen([r"powershell.exe", "$sh = New-Object -COM WScript.Shell" + "\n" +     "$sh.CreateShortcut(\"%s\").TargetPath" % my_data[key].replace("\n", "")], stdout=subprocess.PIPE).communicate()[0]


sys.stdout = old_stdout

shared = mystdout.getvalue()
print shared

回答1:


try removing this sys.stdout = old_stdout line and add stdout=sys.stdout to your main process line for ex like .Popen(***,stdout=sys.stdout)



来源:https://stackoverflow.com/questions/36062041/python-capture-reply-from-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!