将powershell命令作为json字符串传递给子进程

时间:2017-05-01 23:26:23

标签: python json powershell subprocess

我有一个json文件,其中包含按优先级顺序排列的安装程序列表。 STEP_NAME是安装程序的名称,REQUIREMENTS包含首先安装的安装程序列表。

STEP定义安装程序的名称,COMMAND是要安装安装程序时要执行的powershell命令。

{
 {
        "STEP_NAME" : "Second_Installer",
        "REQUIREMENT" :
        [
            {
                "KEY": "First_Installer",
                "TYPE": "STEP"
            },
            {
                "KEY":  "Powershell -ExecutionPolicy Bypass -Command { cd $env:userprofile\\Installers\\Second_Installer; .\\install.bat; }",
                "TYPE": "COMMAND"
            }
        ]
    },
    {
        "STEP_NAME" : "First_Installer",
        "REQUIREMENT" :
        [                
            {
                "KEY": "Powershell -ExecutionPolicy Bypass -Command { &{cd $env:userprofile\\Installers\\First_Installer; .\\install.bat; }}",
                "TYPE": "COMMAND"
            }
        ]
    }
}

我有一个python脚本,用于检查json文件中的密钥是否已安装。 因此,必须首先安装first_installer,然后才能安装second_installer

我的python代码是:

def run_step(self, step):
    # If step was a Requirement, find the matching STEP_NAME
    for item in self.installer_json_data:
        if item['STEP_NAME'] == step:
            step = item

    for req in step['REQUIREMENT']:
        if self.STEP_DONE[step['STEP_NAME']] == False:
            if req['TYPE'] == self.STEP_TYPES[0]:
                self.run_step(req['KEY'])
            elif req['TYPE'] == self.STEP_TYPES[1]:
                commandExecutor = subprocess.Popen(req['KEY'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                print("Installing "+ step['STEP_NAME'])
                commandExecutor.communicate()
                time.sleep(5)
                while commandExecutor.poll() is None:
                    # Decode default byte stream to utf-8 and replace all un-decodable bytes to handle ISO-8859-1
                    output = codecs.decode(commandExecutor.stdout.readline(), 'utf-8', 'replace')
                    #print(output.strip()) # strip removes trailing \n 
                if commandExecutor.returncode == 0:
                    print("Installed " + step['STEP_NAME'])
                    self.STEP_DONE[step['STEP_NAME']] = True
                else:
                    print('Failed to install ' + step['STEP_NAME'])
                    break

但是在执行脚本之后,它表示安装程序已经安装,实际上并非如此。

有人可以建议我做错了吗?

P.S。 - 这些安装程序需要以管理员身份安装

0 个答案:

没有答案