Opening powershell from python

Question:

I would like to open a powershell from my python script, then launch another python script in this newly created powershell.

import subprocess

subprocess.call("start C:\Windows\System32\WindowsPowerShell\v1.0", shell=True) 
# Here, I would like to write this in the new opened powershell : python ./hello_world.py (then press ENTER)

input("end")

Any idea how I can do that ? Thanks and have a good day !

I tried the subprocess.Popen + communicate but nothing was written in my new powershell

Asked By: cecile

||

Answers:

you can just use os.system()

import os

os.system("start powershell python path_to_file") 
# some code
Answered By: Omer Dagry

Another alternative:

import subprocess
subprocess.run(["powershell", "-Command", "python hello-world.py"], capture_output=True, cwd="C:\your\path")

Will output:

CompletedProcess(args=['powershell', '-Command', 'python hello-world.py'], returncode=0, stdout=b'hello worldrn', stderr=b'')

Where stdout=b'hello worldrn' is your output.

Answered By: Pascal

I think subprocess is not intended to interact with active window. but to send stream data to pipeline.

try using pyautogui to interact with Powershell window.

Answered By: Fikra Laksana Putra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.