Write commands with python and execute in powershell

I have a python script that builds commands based on input received through rest. The commands work when printed, copied and pasted into powershell. My question is, how do I get it to actually execute the commands?

So far, I've tried writing commands to a file in the same directory and working like this:

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

      

But I am getting the error:

Traceback (last call last): File "C: /Users/pschaefer/src/python/executePowerShell.py", line 2, at p = subprocess.Popen (["powershell.exe", "test.ps1"], stdout = sys.stdout) File "C: \ Python27 \ lib \ subprocess.py", line 703, in init     errty, 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

deleting ,stdout=sys.stdout1

removes the previous error and now I see

test.ps1 could not be loaded because the startup of \ r \ nscripts is disabled on this system.

I tried switching the command to ".\\test.ps1 Set-ExecutionPolicy -ExecutionPolicy unrestricted"

and still have a problem.

Also, could it be possible to create commands as strings and execute them one by one, rather than creating a .ps1 file? Great recognition to all who can understand this!

+3


source to share


2 answers


Is your computer running a script enabled to run powershell scripts? You can set this using the Set-ExecutionPolicy cmdlet , or you can pass a parameter -ExecutionPolicy Bypass

to run the script at reduced permissions.



+1


source


Running such scripts from the IDE is not supported because the IDEs are redirected stdout

to their own thread, which they usually do not support fileno

in most cases.

Running these commands in a real system shell works.

A workaround that works in both the shell and the IDE is to delete stdout=sys.stdout

, but you can't get error messages or get a result, or even better: redirect the output / error streams using the capabilities Popen

:



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 powershell error.

EDIT: My answer doesn't answer your edit of your question, which shows the actual error message. This Q&A might help you: PowerShell says scripting is disabled on this system. "

+1


source







All Articles