【问题标题】:How to run a line in Powershell in Python 2.7?如何在 Python 2.7 的 Powershell 中运行一行?
【发布时间】:2026-01-17 21:10:01
【问题描述】:

当我在 Powershell 的命令行中输入它时,我有一行 Powershell 脚本运行良好。在我从 Powershell 运行的 Python 应用程序中,我试图将这行脚本发送到 Powershell。

powershell -command ' & {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}'

我知道该脚本有效,因为我已经能够从 Powershell 命令行自行实现它。但是,如果没有“非零退出状态 1”,我无法让 Python 将此行发送到 shell。

import subprocess

product = "765377"
scriptPath = "./uploadImageToBigcommerce.ps1"

def process_image(sku, fileType, searchDirectory, destinationPath, scriptPath):
    psArgs = "Process-Image '"+sku+"' '"+fileType+"' '"+searchDirectory+"' '"+destinationPath+"'"
    subprocess.check_call([create_PSscript_call(scriptPath, psArgs)], shell=True)

def create_PSscript_call(scriptPath, args):
    line = "powershell -command ' & {. "+scriptPath+"; "+args+"}'"
    print(line)
    return line

process_image(product, ".jpg", "C:\Images", "C:\webDAV", scriptPath)

有人有什么想法可以帮忙吗?我试过了:

  • subprocess.check_call()
  • subprocess.call()
  • subprocess.Popen()

也许这只是一个语法问题,但我找不到足够的文档来确认这一点。

【问题讨论】:

  • 我敢打赌你的引用/引用转义在某处是错误的 - print(line) 的输出是什么?
  • 打印(行)输出:powershell -command ' & {。 ./uploadImageToBigcommerce.ps1;处理图像'765377''.jpg''C:\Images''C:\webDAV'}'
  • 我怀疑原来的 PowerShell 命令。它具有嵌套在单引号字符串中的单引号字符串。我对它在 Python 中不起作用并不感到惊讶——我对它曾经起作用感到惊讶。 powershell -command ' & {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 命令内容以' & { 开始,以-Image ' 结束
  • Process-Image 是您计算机上的有效 PowerShell cmdlet 吗?或者它是uploadImageToBigcommerce.ps1的参数,如果前者它可能不在你的路径上,如果后者那么那个分号会破坏东西。
  • @TessellatingHeckler 那我如何将powershell -command " & {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}" 变成一个包含所有引号的字符串?

标签: python-2.7 powershell subprocess


【解决方案1】:

在单引号字符串中使用单引号会破坏字符串。在外面使用双引号,在里面使用单引号,反之亦然,以避免这种情况。本声明:

powershell -command '& {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}'

应该是这样的:

powershell -command "& {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}"

另外,我会使用subprocess.call(和一个引用函数),像这样:

import subprocess

product    = '765377'
scriptPath = './uploadImageToBigcommerce.ps1'

def qq(s):
    return "'%s'" % s

def process_image(sku, fileType, searchDirectory, destinationPath, scriptPath):
    psCode = '. ' + scriptPath + '; Process-Image ' + qq(fileType) + ' ' + \
             qq(searchDirectory) + ' ' + qq(destinationPath)
    subprocess.call(['powershell', '-Command', '& {'+psCode+'}'], shell=True)

process_image(product, '.jpg', 'C:\Images', 'C:\webDAV', scriptPath)

【讨论】: