简体   繁体   中英

Powershell Output as an Array (Python)

Im trying to put the Porwershell Output from Get-Printer | select Name Get-Printer | select Name into an Option Menu. How do i put the Output into an Array for example? Currently the Output is only in One Line. Each Printer is suppost to be one Option.

Im using tkinter. Here is my OptionMenu

variable = StringVar(tkWindow)
variable.set(OptionList[0])
optionPrinter = OptionMenu(framePrinter, variable, *OptionList)
optionPrinter.place(x=5, y=35, width=270, height=25)

My Powershell Process look like this:

process=subprocess.Popen(["powershell","Get-Printer | select Name"],stdout=subprocess.PIPE);
result=process.communicate()[0]

Select -Expand Name seems to be working fine but as you are taking entire output of process into python variable it is treating it as a single line.

You need to split the result into an array like result=process.communicate()[0].splitlines() .

sample code looks like this

from tkinter import *
import subprocess

process=subprocess.Popen(["powershell","Get-Printer | select -Expand Name"],stdout=subprocess.PIPE);
result=process.communicate()[0].splitlines()
print(result[0])
print(result[1])

Not sure if there is any specific reason why you are using PowerShell to search for printers. you can easily do with pypiwin32 module.

After installing this module you can use inline python code to get list of printers with just one line win32print.EnumPrinters(5) .

import win32print

printers = win32print.EnumPrinters(5)
print(printers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM