1

I have a Powershell script that is working and a Python script that is working. I would like to have the Python script run the powershell script for me. I am unable to download any packages because this is on a work computer.

I did look into this before asking and found/tried the following codes:

One:

import subprocess, sys

p = subprocess.Popen(‘powershell.exe -ExecutionPolicy RemoteSigned -file “file location”’, stdout=sys.stdout)
p.communicate()

Two:

import subprocess, sys

p = subprocess.run(‘powershell.exe -ExecutionPolicy RemoteSigned -file “file location”’, shell=True)
p.communicate()

This seems to be the answer on every Reddit/SO question I’ve seen so I’m unsure why it doesn’t work for me. Does anyone know how to fix this? Or any work around?

Thank you in advance!

2
  • You forgot to describe the problem... please describe what exactly are you expecting to happen, and then what actually happens :) Commented May 31, 2022 at 15:21
  • I want the working Python Script I have to run the working Powershell script. When I run the code I have, nothing happens. It doesn’t work. Commented May 31, 2022 at 15:25

1 Answer 1

1
subprocess.run(["powershell", "-Command", cmd], capture_output=True)

On the cmd you can add what ever command you would like to run. Im currently working on a project that includes powershell script running via python and this method works fine for me. One problem though: If you declare this as a variable and you want to iterate through the output, it creates a list of chrs instead of lines(probably easy fix but I didnt have the time to think about a solution).

Sign up to request clarification or add additional context in comments.

1 Comment

You can always serialize the output from the PowerShell command and de-serialize it in Python (my Python is awful but you can see an example here)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.