简体   繁体   中英

Executing PowerShell commands with Python 3.5

I have been working on an issue that requires a Python script to run via the PowerShell command line. The script should pass the command to the command line and save the output. However, I'm running into an issue where some command line arguments are not recognized.

import subprocess
try:
    output = subprocess.check_output\
    (["Write-Output 'Hello world'"], shell=True)
    # (["dir"], shell=True)
except subprocess.CalledProcessError as e:
    print(e.output)
    print('^Error Output^')

If I use the current command with the check_output command, I get an error stating that:

'"Write-Output 'Hello world'"' is not recognized as an internal or external command,
operable program or batch file.

If I just use the "dir" line, the script runs just fine. I'm at odds here as to why this would be happening. This is not the exact script that I'm running, but it produces the same problem on my machine. If I just type the problem command into the command line, it would output "Hello world" onto the new line just as expected.

Any insight as to why this would be happening would be greatly appreciated. If it's of relevance, I would like to not use any sort of admin privilege workaround.

I believe this is because in Windows your default Shell is not PowerShell, you could Execute a Powershell command, calling the executable by executing Powershell with the arguments you need.

For Example


POWERSHELL_COMMAND = r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe'

subprocess.Popen([POWERSHELL_COMMAND,
                  '-ExecutionPolicy', 'Unrestricted',
                  'Write-Output', 'Hello World'],
                  stdout = subprocess.PIPE,
                  stderr = subprocess.PIPE)

if powershell is not in path you could use the full path for the executable or if it's in path you could use just POWERSHELL_COMMAND = "powershell" as command, becareful, with the backslashed windows paths, to avoid errors you could use raw strings.

To verify that you have powershell in path, you could go to the configurations and check, or you could just open a cmd and type powershell and if It works, then you could assume that powershell is in path.

From the docs :

On Windows with shell=True, the COMSPEC environment variable specifies the default shell.

So set COMSPEC=powershell allows to make shell=True use powershell as default instead of cmd

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