給你準(zhǔn)備了一份...我正在使用 Python 的 ; 從我的 Python 代碼中調(diào)用 Powershell 腳本subprocess.Popen。有一個(gè) Powershell 腳本需要一個(gè)初始輸入?yún)?shù),然后在最后按“Enter”鍵才能退出。這給我?guī)砹艘恍┞闊?;Powershell 代碼有點(diǎn)像這樣:$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)我已經(jīng)使用 成功傳遞了輸入proc.stdin.write(usrFileName),但我擔(dān)心這不是正確的方法。考慮到我想要讀取和寫入這一事實(shí),我不想冒使進(jìn)程陷入僵局的風(fēng)險(xiǎn),我很確定這種情況正在發(fā)生。使用過subprocess.call一次或兩次,但我需要使用 proc.poll 進(jìn)行輸出,所以這是行不通的。您可以看到我引入keyboard來修復(fù)輸入,但代碼會在到達(dá)那里之前掛起,所以不確定這是否是正確的方法。長話短說- 我正在尋找一些關(guān)于正確寫入usrFileNamePowershell 的指導(dǎo),首先,讀取 Powershell 的輸出,然后在最后執(zhí)行“按 Enter”。我應(yīng)該明確 close stdin,以便子進(jìn)程停止掛起嗎?我覺得.communicate()或線程是要走的路,但我需要一個(gè)優(yōu)雅的人來給我指路!感謝您的支持。PS 更改 Powershell 不是一個(gè)選項(xiàng),不是我的代碼,只是嘗試使用已經(jīng)存在的東西。謝謝!
使用 Popen 將 Python 變量傳遞給 Powershell 參數(shù)
慕運(yùn)維8079593
2023-07-27 13:53:43