为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Popen 将 Python 变量传递给 Powershell 参数

使用 Popen 将 Python 变量传递给 Powershell 参数

慕运维8079593 2023-07-27 13:53:43
给你准备了一份...我正在使用 Python 的 ; 从我的 Python 代码中调用 Powershell 脚本subprocess.Popen。有一个 Powershell 脚本需要一个初始输入参数,然后在最后按“Enter”键才能退出。这给我带来了一些麻烦;Powershell 代码有点像这样:$usrFileName = read-host "Please enter a file name to save the report"*does some computering**creates some output* #ideally looking to capture this to output, but not the main problem#display task complete to userRead-Host -Prompt "Press Enter to exit" #This is problematic - don't know how to end thisPython代码:from tkinter import *import os, datetimeimport subprocessfrom subprocess import Popen, PIPEfrom keyboard import press_and_releasewindow = Tk()window.title( 'PowerShell Script' )frame = Frame(window)fldrPath = r"C:/Users/paul.sisson/Downloads/Powershell Development/Monthly PMs PowerShell scans/BLDG-7UP-SUNY-Scans/7UP-LAB-A-325/"listbox = Listbox(frame)listbox.configure(width=50)# Get todays date and add the lab name to be piped latertoday = (datetime.datetime.now().strftime('%d%b%Y')).upper()usrFileName = today + "-7UP-A-325"for name in os.listdir(fldrPath):    listbox.insert('end', name)def selection():    fileList = listbox.curselection()    for file in fileList:        keyword = 'Scans'        os.chdir(fldrPath)        proc = subprocess.Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)], bufsize=0,                                universal_newlines=1, stdout=subprocess.PIPE, stdin=subprocess.PIPE)我已经使用 成功传递了输入proc.stdin.write(usrFileName),但我担心这不是正确的方法。考虑到我想要读取和写入这一事实,我不想冒使进程陷入僵局的风险,我很确定这种情况正在发生。使用过subprocess.call一次或两次,但我需要使用 proc.poll 进行输出,所以这是行不通的。您可以看到我引入keyboard来修复输入,但代码会在到达那里之前挂起,所以不确定这是否是正确的方法。长话短说- 我正在寻找一些关于正确写入usrFileNamePowershell 的指导,首先,读取 Powershell 的输出,然后在最后执行“按 Enter”。我应该明确 close stdin,以便子进程停止挂起吗?我觉得.communicate()或线程是要走的路,但我需要一个优雅的人来给我指路!感谢您的支持。PS 更改 Powershell 不是一个选项,不是我的代码,只是尝试使用已经存在的东西。谢谢!
查看完整描述

1 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

交互式Read-Host提示要求每个响应都以换行符终止。

因此,用2 个换行符结束标准输入:一个用于回答文件名提示,另一个用于回答退出提示:

proc.stdin.write(usrFileName + '\n\n')

注意:PowerShell 的 stdout 输出还将包括提示消息和提交的响应,因此在解析输出时需要考虑到这一点;具体来说,stdout 输出将包括以下内容:(
Please enter a file name to save the report: 10Sep2020--7UP-A-325例如), Press Enter to exit: ,加上一个额外的空行,因为退出提示的Read-Host语句的输出未捕获在变量中,因此是隐式输出。


查看完整回答
反对 回复 2023-07-27
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信