![](/img/trans.png)
[英]How to execute powershell script from python with space in the path and parameters
[英]Fetch PowerShell script from GitHub and execute it
在Python中執行PowerShell腳本時遇到問題。
Python本身很簡單,但是它在調用時似乎傳入\\n
並發出錯誤。
['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL
這是完整的代碼:
import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]
print command #<--- this is where I see the \n.
#\n does not appear when I simply 'print script'
所以我有兩個問題:
\\n
正確地將腳本存儲為變量而不寫入磁盤? $script
存儲的$script
?
- 如何避免將
\\n
正確地將腳本存儲為變量而不寫入磁盤?
這個問題本質上是一個重復的這一個 。 以您的示例為例,只需刪除換行符就可以了。 一個更安全的選擇是用分號代替它們。
script = fetch.read().replace('\n', ';')
- 從Python內部調用PowerShell的正確方法是什么,以便它將運行
$script
存儲的$script
?
您的命令必須作為數組傳遞。 同樣,您無法通過-File
參數運行一系列PowerShell語句。 使用-Command
代替:
rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
我相信這是因為您正在打開PowerShell,並且它會自動以特定方式對其進行格式化。
您可以做一個for循環,遍歷命令輸出並打印不帶/ n的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.