将Python变量传递给Suubprocess

rjee0c15  于 2023-03-31  发布在  Python
关注(0)|答案(2)|浏览(136)

我是Python新手,需要帮助解决以下问题。
我试图使子进程执行以下代码,以便在Internet Explorer模式下打开存储在变量中的站点。

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] O sistema não conseguiu localizar o ficheiro especificado
zte4gxcn

zte4gxcn1#

我的机器上没有internet explorer,但此代码无法解析错误:

import subprocess

link = "www.google.com"

def openlink(link: str):
    subprocess.call(f'powershell "$ie = New-Object -com internetexplorer.application; $ie.navigate(\'{link}\')"')

openlink(link)

或者你可以让它绕过powershell,直接用chrome或firefox打开,就像这样:

import subprocess

link = "https://www.google.com"

def openlink(link: str):
    subprocess.call(f'start chrome {link}', shell=True)

openlink(link)
b91juud3

b91juud32#

当您尝试在Python脚本中执行PowerShell命令时,似乎遇到了文件未找到错误。通常我看到此错误发生在子进程模块无法找到“powershell”可执行文件时。
若要修复此错误,您需要提供PowerShell可执行文件的完整路径。您可以通过将第一subprocess.call()修改为:

subprocess.call(['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', '$ie = New-Object -com internetexplorer.application'])

这将执行PowerShell命令并创建一个新的Internet Explorer应用程序。接下来,将第二subprocess.call()修改为:

subprocess.call(['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', f'$ie.navigate("{link}")'])

这将使用f-strings将“link”变量的值插入PowerShell命令,以便Internet Explorer导航到指定的URL。
确保将“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”替换为PowerShell可执行文件的实际路径。

相关问题