首页 > 解决方案 > 从 Python 运行 Powershell 代码 - 传递变量

问题描述

我想通过 Python 在 Windows 中的快速访问中添加一个文件夹。
Python 本身无法做到这一点,但Powershell 可以
每次运行时所述文件夹都会更改,因此我需要将其作为变量传递。

为了最小化我想使用 os.system 的导入。
(与 subprocess.run() 和 subprocess.popen() 相反,因为无论如何我都必须导入系统。)
如果可能的话,我还想保持代码“内联”,而不必存储和引用 .ps1我硬盘上某处的文件。

我拼凑了一些通过谷歌搜索不起作用的东西:

import os

myfolder = "C:/Windows"
os.system("powershell.exe [$qa = New-Object -ComObject shell.application && $qa.NameSpace('%s').Self.InvokeVerb('pintohome')]"  % (myfolder))

我收到以下错误消息:

In Zeile:1 Zeichen:2
+ [$qa = New-Object -ComObject shell.application
+  ~
Der Typname nach "[" fehlt.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingTypename

1.) 如何正确地告诉 Python 调用 powershell?
2.) 如何添加多行代码使其在同一环境中执行?
3.) 如何正确传递文件夹变量?

作为额外的奖励,我将如何在执行代码时隐藏 powershell 窗口?

标签: pythonwindowspowershell

解决方案


import os
myfolder = r"C:\Windows"   # use backslashes!!!

os.system("powershell.exe \"$qa = New-Object -ComObject shell.application; $qa.NameSpace( '%s').Self.InvokeVerb( 'pintohome')\""  % (myfolder))
#                         ↑↑ command as string, see below

解释。PowerShell 中的命令分隔符是;分号)。请注意,左方括号和右方括号([和) 是以下描述中可选]性的元符号:

powershell.exe -?

PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
    [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
    [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
    [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
    [-ConfigurationName <string>]
    [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
    [-Command { - | <script-block> [-args <arg-array>]
                  | <string> [<CommandParameters>] } ]

…

-Command
    Executes the specified commands (and any parameters) as though they were
    typed at the Windows PowerShell command prompt, and then exits, unless
    NoExit is specified. The value of Command can be "-", a string. or a
    script block.

    If the value of Command is "-", the command text is read from standard
    input.

    If the value of Command is a script block, the script block must be enclosed
    in braces ({}). You can specify a script block only when running PowerShell.exe
    in Windows PowerShell. The results of the script block are returned to the
    parent shell as deserialized XML objects, not live objects.

    If the value of Command is a string, Command must be the last parameter
    in the command , because any characters typed after the command are
    interpreted as the command arguments.

    To write a string that runs a Windows PowerShell command, use the format:
        "& {<command>}"
    where the quotation marks indicate a string and the invoke operator (&)
    causes the command to be executed.

推荐阅读