Amaryllis Ninja
Amaryllis Ninja

Reputation: 55

Subprocess opens PowerShell, runs commands, then dies

I've written some code that uses the Python subprocess module to open a PowerShell window, then run a command in that same window. The PS window opens, then almost immediately closes. The code below will open a PS window and leave it open if I removed the second item from cmd.

import subprocess
cmd = ['powershell', 'ls']
prompt = subprocess.Popen(cmd, stdin=subprocess.PIPE)

Upvotes: 1

Views: 622

Answers (3)

JosefZ
JosefZ

Reputation: 30123

Add -noexit argument as follows (-noprofile is not mandatory):

import subprocess
cmd = ['powershell', '-noprofile', '-noexit', '&', 'ls *.csv']
prompt = subprocess.call ( cmd )

Result:

Powershell from python

Upvotes: 2

tbhaxor
tbhaxor

Reputation: 1943

Its because you forgot to communicate with process Simply add a line

output, error = prompt.communicate()  # this is to start the process
print(output) # add stdout=subprocess.PIPE
print(error)  # add stderr=subprocess.PIPE

PS: I can't help you with powershell because i don't know powershell

Upvotes: 0

MrName
MrName

Reputation: 2529

Any reason to not use subprocess.call instead? I think it would do exactly what you want.

Upvotes: 0

Related Questions