![](/img/trans.png)
[英]Passing Python variable to Powershell parameter using Popen
[英]Passing Python variable to Powershell parameter using Python's Popen
我正在使用Python的子Popen
在Python腳本中調用Powershell腳本。 Powershell腳本需要兩個輸入參數: -FilePath
和-S3Key
。 它將文件上傳到AWS S3服務器。 如果我輸入硬編碼字符串,則腳本可以工作。
os.Popen([r'C:\\\\WINDOWS\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath \\"C:\\TEMP\\test.txt\\" -S3Key \\"mytrialtest/test.txt\\"'])
但是,如果我嘗試傳入Python字符串變量,則Powershell腳本會出錯,提示它找不到文件名變量指定的文件。
filename = 'C:\TEMP\test.txt'
uploadkey = 'mytrialtest/test.txt'
os.Popen([r'C:\\\\WINDOWS\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath \\"filename\\" -S3Key \\"uploadkey\\"'])
任何幫助將不勝感激。 謝謝。
我知道,這是一個古老的問題,因此,這是給那些通過google找到此問題的人的:
評論中提到的解決方案存在一些風險(字符串注入),並且如果涉及特殊字符,則可能無法正常工作。 更好:
import subprocess
filename = r'C:\TEMP\test.txt'
uploadkey = 'mytrialtest/test.txt'
subprocess.Popen(['powershell',"-ExecutionPolicy","RemoteSigned","-File", './Upload.ps1', '-FilePath:', filename , '-S3Key:', uploadkey])
請注意,在參數名稱后面附加了:
-在大多數情況下,如果沒有:
,它也可以使用,但是如果該值以短划線開頭,則會失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.