Hi there,
I'm trying to run PowerShell by Python, but my PowerShell window closes automatically after finishing, even if I add the "No-Exit".
Could anyone please help me solve this problem? Thanks a lot!
Below is my code:
import subprocess
powershell_command = 'choco update haskell-stack -NoExit'
powershell_process = subprocess.Popen(["powerShell", "-Command", "-NoExit", powershell_command], creationflags=subprocess.CREATE_NEW_CONSOLE)
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
I'm not familiar with Python, but you need to pass the command text after the -Command switch.
import subprocess
powershell_command = 'choco update haskell-stack'
powershell_process = subprocess.Popen(["powerShell", "-NoExit", "-Command", powershell_command], creationflags=subprocess.CREATE_NEW_CONSOLE)
You might also need to put brackets {} around the command text.
powershell_command = '{choco update haskell-stack}'
Does python process single and double quotes differently? If PS just outputs the command, then it may be that your powershell_command variable includes those single quotes which PS would interpret as plain text output.
Trace it and see how PS is getting launched.
Download and run Process Monitor.
https://learn.microsoft.com/en-us/sysinternals/downloads/procmon
In the Filter menu, set an include entry for "Process name is powershell.exe" and start the trace. Then run your Python code.
We want to see what command line arguments are being passed to PS.
Here is the test that I ran. from a command prompt, I started PS with a simple sleep command.
But if I put single quotes around the command, PS just displays the text.
You can see how this works by running these commands in a command prompt..
start powershell -noexit -command 1+1
start powershell -noexit -command '1+1'
start powershell -noexit -command "1+1"
Dear MotoX80
Thank you very much for your help! I realised that the answer you gave me initially was correct; I just made a stupid mistake (never mind). Now my problem is solved perfectly, thank you!
Here's my final code. I hope it can be useful to others who may come across it.
command = 'choco upgrade ghc'
powershell_process = subprocess.Popen(["powershell", "-NoExit", "-Command", command], creationflags=subprocess.CREATE_NEW_CONSOLE)