Python 捕获来自 powershell 的回复

Python Capture reply from powershell

下面的代码在手动输入时有效,但是当我 运行 program.py 没有任何打印。我的最终目标是从用户 pc 中检索此数据,以创建一种重新创建快捷方式的简单方法....我的用户不知何故失去了他们 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

尝试删除此 sys.stdout = old_stdout 行并将 stdout=sys.stdout 添加到您的主流程行中,例如 .Popen(***,stdout=sys.stdout)