如何在 Python 2.7 中 运行 Powershell 中的一行?

How to run a line in Powershell in Python 2.7?

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

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

我知道该脚本有效,因为我已经能够从 Powershell 命令行自行执行它。但是,如果没有 "non-zero exit status 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)

有没有人有什么想法可以帮助?我试过:

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

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

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)