【问题标题】:Python Capture reply from powershellPython 捕获来自 powershell 的回复
【发布时间】:2016-07-03 21:20:17
【问题描述】:

下面的代码在手动输入时有效,但是当我运行 program.py 时没有打印。我的最终目标是从用户 pc 中检索这些数据,以创建一种简单的方法来重新创建快捷方式....我的用户不知何故失去了它们,哈哈

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__.write(shared),而不是最后的print shared
  • 感谢您的回复。但是我尝试了仍然没有得到任何东西。我认为首先没有任何东西被捕获。它很奇怪,但在尝试了很多东西之后,打印是空的,没有错误只是空的。

标签: python powershell stringio communicate cstringio


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 2013-01-21
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多