首页 > 解决方案 > 在 Python 中运行 Powershell 命令(SyntaxError:无效语法)

问题描述

我正在尝试在系统上执行代码,该代码将文件从直接链接下载到%appdata%Windows 上的目录。

我的代码:

def downloadfile():
    mycommand = "powershell -command "$cli = New-Object System.Net.WebClient;$cli.Headers['User-Agent'] = {};$cli.DownloadFile('https://drive.google.com/uc?export=download&id=19LJ6Otr9p_stY5MLeEfRnA-jD8xXvK3m', '%appdata%\putty.exe')""
    down = subprocess.call(mycommand)



downloadfile()

但我得到这个错误:

文件“searchmailfolder.py”,第 4 行 mycommand =“powershell -command”$cli = New-Object System.Net.WebClient;$cli.Headers['User-Agent'] = 'myUserAgentString';$cli.DownloadFile(' https://drive.google.com/uc?export=download&id=19LJ6Otr9p_stY5MLeEfRnA-jD8xXvK3m ', '%appdata%\putty.exe')"" ^ SyntaxError: 无效语法

标签: pythonpowershellcmddownloadsubprocess

解决方案


希望这有帮助。导入子进程和系统。然后尝试类似“command = subprocess.Popen(["powershell.exe","user_command.ps1"],stdout=sys.stdout) command.communicate()" 尝试将代码放入 .ps1 文件


推荐阅读