【问题标题】:Passing Python variable to Powershell parameter using Python's Popen使用 Python 的 Popen 将 Python 变量传递给 Powershell 参数
【发布时间】:2013-10-18 23:48:57
【问题描述】:

我正在使用 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\"'])

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

【问题讨论】:

  • 尝试定义filename = '"' + r"C:\TEMP\test.txt" + '"'。为uploadkey 做同样的事情。
  • 我发现了问题所在。这是解决方案:
  • 谢谢大卫。这是我找到的解决方案: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 ',文件名,'-S3Key ',uploadkey])

标签: python powershell parameter-passing popen


【解决方案1】:

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

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

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

注意:附加到参数名称 - 在大多数情况下,它也可以在没有:的情况下工作,但如果值以破折号开头,它将失败。

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 2016-10-27
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多