Python将变量传入Subprocess调用PowerShell打开IE网页报错求助
问题与解决
原问题代码
import subprocess # 原代码遗漏导入,补充在此 link = "www.google.com" def openlink(link: str): subprocess.call('"powershell" $ie = New-Object -com internetexplorer.application') subprocess.call('powershell' '$ie.navigate(link)')
报错信息(翻译后)
Traceback (most recent call last): File "C:\Users\luiis\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "C:\Users\luiis\Desktop\IMPORTANTE\Softwares Luis Teixeira\Portal Links\main.py", line 10, in open subprocess.call('powershell' '$ie.navigate(link)') File "C:\Users\luiis\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 345, in call with Popen(*popenargs, **kwargs) as p: File "C:\Users\luiis\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 971, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\luiis\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1440, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] 系统找不到指定的文件
错误原因
- subprocess参数格式错误:将
'powershell'与命令字符串拆分为两个参数传入,Python会把'powershell'当作执行程序,后续字符串当作程序路径,导致文件找不到。 - 进程上下文独立:两次
subprocess.call启动的是独立PowerShell进程,第一次创建的$ie对象无法在第二次进程中复用。 - 变量传递失败:Python的
link变量未正确传入PowerShell命令,PowerShell无法识别该变量。
修正后的代码
import subprocess link = "www.google.com" def openlink(link: str): # 将所有PowerShell逻辑放在同一进程执行,用f-string传递Python变量 ps_command = f''' $ie = New-Object -com internetexplorer.application $ie.Visible = $true # 必须设置为true,否则IE窗口默认隐藏 $ie.Navigate("{link}") ''' # 正确参数格式:可执行文件+命令参数 subprocess.call(["powershell", "-Command", ps_command]) openlink(link)
补充说明
["powershell", "-Command", ps_command]是subprocess推荐的安全写法,可避免shell注入风险。- Windows 11系统可能需要手动启用Internet Explorer组件,才能正常创建
internetexplorer.application对象。
内容的提问来源于stack exchange,提问作者Luis Teixeira
相关产品推荐
相关产品推荐

