如何在Python中使用定义的变量运行特定的Powershell命令并打印输出?

2024-05-16 20:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行从Python到Powershell的特定命令:

该命令在Powershell中按预期工作。Powershell中的命令如下所示:

 gpt .\Method\gpt_scripts\s1_cal_deb.xml -t .\deburst\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E_Cal_deb_script.dim .\images\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E.zip

Powershell输出:

enter image description here

os.getcwd()

'C:\\Users\\Ishack\\Documents\\Neta-Analytics\\Harvest Dates\\S1_SLC_Processing'

当前目录与PowerShell中的相同

我试过这样的方法:

import subprocess


process = 'gpt .\Method\gpt_scripts\s1_cal_deb.xml -t .\deburst\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E_Cal_deb_script.dim .\images\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E.zip'

process = subprocess.Popen(['powershell.exe', '-NoProfile', '-Command', '"&{' + process + '}"'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)


process

输出:

<subprocess.Popen at 0x186bb202388>

但当我按下enter键时,没有得到响应,我希望Python像在Powershell中一样打印输出。我研究了其他类似的问题,但仍然没有解决问题的办法

谢谢

伊沙克


Tags: 命令scriptsdebxmlprocessmethodcalsubprocess
1条回答
网友
1楼 · 发布于 2024-05-16 20:02:02
import os
os.system("powershell.exe -ExecutionPolicy Bypass -File .\SamplePowershell.ps1")

SamplePowershell.ps1

Write-Host "Hello world"
hostname

这对我有用。文件SamplePowershell.ps1中的命令

如果要使用子流程

import subprocess
k=subprocess.Popen('powershell.exe hostname', stdout=subprocess.PIPE, stderr=subprocess.PIPE);
print(k.communicate())

相关问题 更多 >