Python Capture reply from powershell

277 Views Asked by At

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

There are 1 best solutions below

0
Manjit Ullal On BEST ANSWER

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)