0

I'm trying to work with Powershell in python and work with get-disk command I tried to work with stdout and print it but the value of it is gone right after I use the Communicate() function Here's my code:

proc = subprocess.Popen(r"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe", stdin = subprocess.PIPE,
                    stdout = subprocess.PIPE)
stdout, stderr = proc.communicate('get-disk')
print stdout

Any suggestions?

3
  • 1
    Why are you using two scripting languages when you can do everything with PowerShell on its own? PS C:\> Get-Disk bam. done. Nov 7, 2017 at 19:48
  • you are just opeining a powershell process without parameters. I am not aware of any process that by default reads input parameters from stdin... did you google that? what about this? stackoverflow.com/questions/2768790/stdin-to-powershell-script
    – Harry
    Nov 7, 2017 at 19:50
  • Use this link https://stackoverflow.com/a/75175057/12780274
    – henrry
    Jan 19, 2023 at 16:05

3 Answers 3

0

You could try the following, which will read the std output of your process when starting the process with

proc=Popen('Some process',stdout=subprocess.PIPE)

stdout = proc.stdout.read()
0

You can do this as done below

from subprocess import Popen
from subprocess import Popen, CREATE_NEW_CONSOLE,PIPE,STDOUT
import subprocess
command="powershell.exe get-disk"

#This will open the command in a new console
proc=Popen(command,creationflags=CREATE_NEW_CONSOLE,stdout=subprocess.PIPE)
read_stdout=[]
for lines in proc.stdout.readlines():
    read_stdout.append(lines)

print read_stdout
0

I recomend proc.stdout.read() instead of proc.communicate()

What you want is something like this:

import subprocess

cmd = r"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe get-disk"
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
print(proc.stdout.read())
proc.stdout.close()

Not the answer you're looking for? Browse other questions tagged or ask your own question.