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

2024-07-08 10:13:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python的子进程Popen在Python脚本中调用Powershell脚本。Powershell脚本需要两个输入参数:-FilePath-S3Key。它上传一个文件到aws3服务器。如果我传入硬编码字符串,脚本就可以工作。在

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变量指定的文件。在

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\"'])

任何帮助都将不胜感激。谢谢。在


Tags: 文件字符串testtxt脚本oswindowsfilename
1条回答
网友
1楼 · 发布于 2024-07-08 10:13:09

我知道,这是一个老问题,所以这是给那些通过谷歌找到这个问题的人:

注释中提到的解决方案有一些风险(字符串注入),如果涉及特殊字符,可能无法工作。更好:

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])

请注意,参数名后面附加了:,在大多数情况下,它也可以不使用:,但是如果值以破折号开头,它将失败。在

相关问题 更多 >

    热门问题