本文介绍了带有 selenium 的 Python 程序(webdriver)不能作为单个和 noconsole exe 文件(pyinstaller)工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的python代码:

The following is my python code:

## t.py ##

from tkinter import messagebox
from tkinter import *
from selenium import webdriver

def clicked():
    iedriver = "C:\\Program Files\\Internet Explorer\\IEDriverServer.exe"
    try:
        driver=webdriver.Ie(iedriver)
    except Exception as e:
        messagebox.showerror("Error",e)
    driver.get('www.baidu.com')
Top=Tk()
Button(Top,text='Click Me',command=clicked).pack()
Top.mainloop()

这很好用,但是当我使用 PyInstaller(t.spec) 将其转换为单个 .exe 文件时:

This works fine, but when I convert this to a single .exe file with PyInstaller(t.spec):

# -*- mode: python -*-

block_cipher = None


a = Analysis(['D:\\program\\Python\\t.py'],
         pathex=['D:\\program\\Python'],
         binaries=None,
         datas=None,
         hiddenimports=[],
         hookspath=None,
         runtime_hooks=None,
         excludes=None,
         win_no_prefer_redirects=None,
         win_private_assemblies=None,
         cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)
exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='t',
      debug=False,
      strip=None,
      upx=False,
      console=0 , icon='D:\\program\\Python\\logo\\t.ico')

点击按钮运行会提示如下错误:似乎无法识别 IEDriver 可执行文件

It will prompt the following error when clicking the button to run:Seems that IEDriver executable can't be recognized

当我在spec文件中将选项console=0"更改为console=1"时,点击按钮后IE可以运行.知道为什么设置了console=0"时 IE 无法运行吗?

When I change the option "console=0" to "console=1" in the spec file, IE can be run after clicking the button. Any idea why IE can't be run when "console=0" is set?

推荐答案

我想我通过修改 selenium 包中的 Service class 解决了这个问题.我不确定这是否是 selenium(2.47.3) 的错误.原始代码在调用 subprocess.Popen 函数时仅重定向 stdoutstderr 而不是 stdin.

I think I fixed this by modifying the Service class in selenium package. I'm not sure whether this is a bug for selenium(2.47.3). The original code is only redirecting stdout and stderr but not stdin when it calls subprocess.Popen function.

我修改了以下代码:

self.process = subprocess.Popen(cmd,
                stdout=PIPE, stderr=PIPE)

致:

self.process = subprocess.Popen(cmd, stdin=PIPE,
                stdout=PIPE, stderr=PIPE)

那么问题就解决了.

这篇关于带有 selenium 的 Python 程序(webdriver)不能作为单个和 noconsole exe 文件(pyinstaller)工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:18