繁体   English   中英

使用Python的Popen将Python变量传递给Powershell参数

[英]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","RemoteSig‌​ned","-File", './Upload.ps1', '-FilePath:', filename , '-S3Key:', uploadkey])

请注意,在参数名称后面附加了: -在大多数情况下,如果没有: ,它也可以使用,但是如果该值以短划线开头,则会失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM