从 Python 运行 PowerShell 脚本 [英] Running PowerShell Script from Python

查看:60
本文介绍了从 Python 运行 PowerShell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行 Powershell 脚本(请查看下面的内容)首先,我的 Powershell 脚本在使用 Powershell 运行时工作正常,给出了预期的结果(关闭所有打开的文件夹),但我必须从 Python 脚本中调用它,因此我尝试使用 subprocess.Popen,但我有错误 :"io.UnsupportedOperation: 文件号"

I'm trying to run a Powershell Script ( check below ) First remark, my Powershell script, when running with Powershell works fine, giving the expected result ( closing all open folders ) , but I have to call this from a Python script, therefore I tried using subprocess.Popen, but I'm having the error : "io.UnsupportedOperation: fileno"

已经尝试了几种不同的方法,但建议的解决方案不起作用.

Tried several different things already, but the solutions suggested aren't working.

我正在尝试调用以下 Powershell 脚本:

I'm trying to call the following Powershell Script :

$shell = New-Object -ComObject Shell.Application 
$shell.Windows() | Format-Table LocationName, LocationURL 
$window = $shell.Windows() 
$window | ForEach-Object { $_.Quit() }

这个想法是关闭所有打开的文件夹,直接用 Powershell 运行就可以了.

The idea is to close all the open folders, and directly running with Powershell works as expected.

然后我尝试从 Python 调用这个脚本:

Then I tried to call this script from Python :

p = subprocess.Popen(['powershell.exe', 'C:\\Users\\(correct subfolders)\\TEST.ps1'])

p = subprocess.Popen(['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', 'C:\\Users\\(correct subfolders)\\TEST.ps1'])

并且他们不返回错误,一个 cmd 窗口打开,但没有任何反应.然后我尝试了以下操作:

and they don't return errors, a cmd window opens, but nothing happens. Then I tried the following :

p = subprocess.Popen(['powershell.exe', 'C:\\Users\\(correct subfolders)\\TEST.ps1'], stdout=sys.stdout)

但是我有以下错误(检查下面)

But I have the following error ( check below )

File "<pyshell#15>", line 1, in <module>
    p = subprocess.Popen(['powershell.exe', 'C:\\Users\\FernanP\\Desktop\\TEST.ps1'], stdout=sys.stdout)
  File "C:\Users\FernanP\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 667, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "C:\Users\FernanP\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 922, in _get_handles
    c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
io.UnsupportedOperation: fileno

我在这里查看了类似的问题,人们说枕头版本,但我目前使用的是 6.1.0,所以应该没有问题.

I looked into similar Questions here, and people said about the Pillow version, but I'm currently using 6.1.0, so it should not be a problem.

因此,或者直接在 Python 中等效于 powershell 脚本就足够了,或者是一种处理此问题的方法.希望我充分告知.韩国

Therefore, either an equivalent to the powershell script directly in Python would be enough, or a way to deal with this issue. Hope I informed sufficiently. KR

推荐答案

这里我创建了自己的function 运行任何 powershell script带有它的参数

Here I have created my own function to run any powershell script with its parameters

import subprocess  # IMPORT FOR SUB PROCESS . RUN METHOD

POWERSHELL_PATH = "powershell.exe"  # POWERSHELL EXE PATH
ps_script_path = "C:\\PowershellScripts\\FTP_UPLOAD.PS1"  # YOUR POWERSHELL FILE PATH


class Utility:  # SHARED CLASS TO USE IN OUR PROJECT

    @staticmethod    # STATIC METHOD DEFINITION
    def run_ftp_upload_powershell_script(script_path, *params):  # SCRIPT PATH = POWERSHELL SCRIPT PATH,  PARAM = POWERSHELL SCRIPT PARAMETERS ( IF ANY )

        commandline_options = [POWERSHELL_PATH, '-ExecutionPolicy', 'Unrestricted', script_path]  # ADD POWERSHELL EXE AND EXECUTION POLICY TO COMMAND VARIABLE
        for param in params:  # LOOP FOR EACH PARAMETER FROM ARRAY
            commandline_options.append("'" + param + "'")  # APPEND YOUR FOR POWERSHELL SCRIPT

        process_result = subprocess.run(commandline_options, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True)  # CALL PROCESS

        print(process_result.returncode)  # PRINT RETURN CODE OF PROCESS  0 = SUCCESS, NON-ZERO = FAIL  
        print(process_result.stdout)      # PRINT STANDARD OUTPUT FROM POWERSHELL
        print(process_result.stderr)      # PRINT STANDARD ERROR FROM POWERSHELL ( IF ANY OTHERWISE ITS NULL|NONE )

        if process_result.returncode == 0:  # COMPARING RESULT
            Message = "Success !"
        else:
            Message = "Error Occurred !"

        return Message  # RETURN MESSAGE

这篇关于从 Python 运行 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆