【发布时间】:2019-08-02 16:38:54
【问题描述】:
我一直在尝试从我的主要 python 程序中执行一个 powershell 脚本。该脚本已经过测试,可直接通过 powershell 运行。然而,当我启动一个进程以在 python 中执行它时,情况并非如此。
我尝试了多种方法,确保 powershell 没有限制我的执行策略(不受限制)。我也尝试了一个批处理文件,但是当我使用 python 执行批处理文件时它出错了
com = os.path.join( ".", 'test2.ps1 -in "C:','Users','kbrab','Desktop','Test','test.csv" -out "C:','Users','kbrab','Desktop','Test','OSReport.xlsx"')
print(com)
p = subprocess.Popen(['powershell.exe', '-ExecutionPolicy', 'unrestricted',
com],stderr=subprocess.PIPE)
out = p.communicate()
print(out)
com 字符串具有正确的路径,并按如下方式打印:
.\test2.ps1 -in "C:\Users\kbrab\Desktop\Test\test.csv" -out "C:\Users\kbrab\Desktop\Test\OSReport.xlsx"
想我还会添加 powershell 脚本:
param([string]$in = "in", [string]$out = "out")
Import-Module ImportExcel
Write-Host "Arg: $in"
Write-Host "Arg: $out"
Import-CSV $in | Export-Excel $out `
-IncludePivotTable `
-PivotRows 'BName' `
-PivotData @{'MEMBERNBR'='count'}
错误信息是:
(None, b"Export-Excel : The term 'Export-Excel' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\kbrab\Desktop\Test\test2.ps1:5 char:18 + Import-CSV $in | Export-Excel $out ` + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Export-Excel:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException")
powershell 脚本自己导入一个 csv 然后导出一个数据透视表,直接通过 powershell 执行时它可以正常工作。
非常感谢任何帮助,谢谢
更新 1
将导入添加到 powershell 脚本后的第二个错误
(None, b"Import-Module : The specified module 'ImportExcel' was not loaded because no valid module file was found in any module directory. At C:\Users\kbrab\Desktop\Test\test2.ps1:2 char:1 + Import-Module ImportExcel + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (ImportExcel:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand Export-Excel : The term 'Export-Excel' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\kbrab\Desktop\Test\test2.ps1:6 char:18 + Import-CSV $in | Export-Excel $out ` + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Export-Excel:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException")
仅在 powershell 上测试,仍然有效
【问题讨论】:
标签: python-3.x powershell subprocess