Windows PowerShell 由數(shù)十個(gè)內(nèi)置 cmdlet 組成,它們提供了豐富的功能集。 其中一些功能是獨(dú)一無二的,只能通過 PowerShell 獲得; 因此,如果我們能夠在 Python 等其他編程語言中使用 PowerShell 腳本,那將非常有用。
本文將重點(diǎn)討論從 Python 代碼執(zhí)行 PowerShell 邏輯。
Python subprocess.Popen()方法
在Python中,可以使用 subprocess.Popen()
方法執(zhí)行外部程序。 subprocess 模塊由幾個(gè)比舊 os 模塊中可用的方法更有效的方法組成; 因此,建議使用 subprocess 模塊而不是 os 模塊。
由于我們將從 Python 程序運(yùn)行 PowerShell 代碼,因此最方便的方法是在 subprocess 模塊中使用 Popen 類。 它創(chuàng)建一個(gè)單獨(dú)的子進(jìn)程來執(zhí)行外部程序。
需要記住的一件事是這個(gè)過程依賴于平臺(tái)。
每當(dāng)您調(diào)用 subprocess.Popen()
時(shí),都會(huì)調(diào)用 Popen 構(gòu)造函數(shù)。 它接受多個(gè)參數(shù),如下所示。
subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
參數(shù) args 用于傳遞啟動(dòng)外部程序的命令。 有兩種方法可以傳遞命令及其參數(shù)。
- 作為參數(shù)序列
Popen(["path_to_external_program_executable", "command_args1", "command_args2", ...])
- 作為單個(gè)命令字符串
Popen('path_to_external_program_executable -command_param1 arg1 -command_param2 arg2 ...')
建議使用 Popen 構(gòu)造函數(shù)使用參數(shù)序列。
下一個(gè)重要參數(shù)是 stdout 參數(shù),我們將在下一節(jié)中使用它。 這指定了進(jìn)程應(yīng)使用的標(biāo)準(zhǔn)輸出。
使用 Popen() 方法從 Python 程序中運(yùn)行 PowerShell 腳本
首先,創(chuàng)建一個(gè)打印到控制臺(tái)窗口的簡單 PowerShell 腳本。
Write-Host 'Hello, World!'
我們將其保存為 sayhello.ps1。
接下來,我們將創(chuàng)建一個(gè) Python 腳本 runpsinshell.py。 由于我們將使用 subprocess.Popen()
命令,因此我們必須首先導(dǎo)入 subprocess 模塊。
import subprocess
然后我們將使用 args 和 stdout 參數(shù)調(diào)用 Popen 構(gòu)造函數(shù),如下所示。
p = subprocess.Popen(["powershell.exe", "D:\\codes\\sayhello.ps1"], stdout=sys.stdout)
正如您所看到的,參數(shù)已作為序列傳遞,這是推薦的方式。 第一個(gè)參數(shù)是外部程序可執(zhí)行文件名稱,第二個(gè)參數(shù)是先前創(chuàng)建的 PowerShell 腳本的文件路徑。
另一件要記住的重要事情是我們應(yīng)該將標(biāo)準(zhǔn)輸出參數(shù)指定為 sys.stdout。 要在 Python 程序中使用 sys.stdout,我們還必須導(dǎo)入 sys 模塊。
最終程序應(yīng)如下所示。
import subprocess, sys
p = subprocess.Popen(["powershell.exe", "D:\\codes\\sayhello.ps1"], stdout=sys.stdout)
p.communicate()
最后,我們來運(yùn)行Python程序,如下所示。
python .\runpsinshell.py
輸出:
正如預(yù)期的那樣,PowerShell 腳本已從 Python 代碼執(zhí)行并打印了 Hello, World! 字符串到 PowerShell 窗口。文章來源:http://www.zghlxwxcb.cn/news/detail-795180.html
還可以通過將 Popen 構(gòu)造函數(shù)參數(shù)作為單個(gè)字符串傳遞來編寫 Python 程序。文章來源地址http://www.zghlxwxcb.cn/news/detail-795180.html
import subprocess, sys
p = subprocess.Popen('powershell.exe -ExecutionPolicy RemoteSigned -file "D:\\codes\\sayhello.ps1"', stdout=sys.stdout)
p.communicate()
到了這里,關(guān)于從 Python 程序中運(yùn)行 PowerShell 腳本的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!