【问题标题】:How to Run a Specific Powershell Command Within Python with a Defined Variable and Print Output?如何在 Python 中使用定义的变量运行特定的 Powershell 命令并打印输出?
【发布时间】:2020-05-13 20:22:30
【问题描述】:

我正在尝试从 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 输出:

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>

但是当我按下回车时,我没有得到任何响应,我希望 Python 能够像在 Powershell 中一样打印输出。我研究了其他类似的问题,但仍然没有解决问题。

谢谢,

伊哈克

【问题讨论】:

标签: python string powershell subprocess getcwd


【解决方案1】:
import os
os.system("powershell.exe -ExecutionPolicy Bypass -File .\SamplePowershell.ps1")

SamplePowershell.ps1

Write-Host "Hello world"
hostname

这对我有用。 SamplePowershell.ps1.

文件中的命令

如果你想使用 subprocess

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

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2018-07-24
    • 2021-10-04
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多