cecile
cecile

Reputation: 11

Opening powershell from python

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

Upvotes: 0

Views: 1057

Answers (3)

Omer Dagry
Omer Dagry

Reputation: 567

you can just use os.system()

import os

os.system("start powershell python path_to_file") 
# some code

Upvotes: 0

Fikra Laksana Putra
Fikra Laksana Putra

Reputation: 38

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.

Upvotes: 0

Pascal
Pascal

Reputation: 1246

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 world\r\n', stderr=b'')

Where stdout=b'hello world\r\n' is your output.

Upvotes: 1

Related Questions