简体   繁体   中英

Write commands with python and execute in powershell

I have a python script that builds commands based off input gotten via rest. The commands work when printed out and copied and pasted into powershell. My question is how to make it actually execute the commands?

So far I have tried writing the commands to a file in the same directory and running like so:

import subprocess, sys
p = subprocess.Popen(["powershell.exe", "test.ps1"],stdout=sys.stdout)
p.communicate()

But I get an error:

Traceback (most recent call last): File "C:/Users/pschaefer/src/python/executePowerShell.py", line 2, in p = subprocess.Popen(["powershell.exe", "test.ps1"],stdout=sys.stdout) File "C:\\Python27\\lib\\subprocess.py", line 703, in init errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr) File "C:\\Python27\\lib\\subprocess.py", line 850, in _get_handles c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) UnsupportedOperation: fileno

Update

removing ,stdout=sys.stdout1 gets rid of the previous error and now I see

test.ps1 cannot be loaded because running \\r\\nscripts is disabled on this system.

I have tried switching the command to ".\\\\test.ps1 Set-ExecutionPolicy -ExecutionPolicy unrestricted" and still have the issue.

Also, would it be possible to build the commands as strings and execute them one by one as built instead of creating a .ps1 file? Big kudos to anyone that can figure that out!

Is your machine you are running the script on enabled to run powershell scripts? You can set this via the Set-ExecutionPolicy cmdlet, or you can pass the -ExecutionPolicy Bypass parameter to run the script with lowered permissions.

Running such scripts from an IDE isn't supported because IDEs redirect stdout to their own stream, which doesn't support fileno properly most of the time.

Running those commands in a real system shell works, though.

The workaround which works in both shell & IDE is to remove stdout=sys.stdout but you can't get the error messages or retrieve the output, or even better: redirect the output/error streams using Popen capabilities:

import subprocess, sys
p = subprocess.Popen(["powershell.exe", "test.ps1"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err = p.communicate()
print(out,err)

on my machine, since test.ps1 doesn't exist, I get a clear powershell error message.

EDIT: my answer doesn't answer to your edit of your question which shows the actual error message now. This Q&A may help you: PowerShell says "execution of scripts is disabled on this system."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM