【问题标题】:Python code works but executable (made using py2exe) doesn'tPython 代码有效,但可执行文件(使用 py2exe 制作)无效
【发布时间】:2017-11-06 14:07:58
【问题描述】:

我编写了一个 Python 程序,它使用 Selenium 从某些网站获取数据。这意味着我的代码需要 3 个文件:(1)带有一些输入参数的文本文件(2)firefox 二进制文件和(3)壁虎驱动程序

现在为了与我的同事分享,我已使用 py2exe 将其转换为可执行文件。

从 shell 执行的程序运行良好。但是,当通过可执行文件执行相同操作时,会导致各种错误 - 这些错误 - (1) 未找到输入参数文件 (2) 未找到 gecko 驱动程序 (3) Windows 处理错误 6(并非所有这些错误每次都会发生) 如何确保它也可以作为可执行文件运行?

代码摘录:

gdir = str(os.path.realpath('.'))
gdir = gdir.replace('\\','\\\\')
inpArgPath = gdir + '\\\\inputArguments.txt'

ffpath = 'FirefoxPortable/App/Firefox64/firefox.exe'
binary = webdriver.firefox.firefox_binary.FirefoxBinary(ffpath)
gecko = gdir + '\\\\gecko\\\\geckodriver64.exe'

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.forbid_open_with",True)
fp.set_preference("browser.download.altClickSave",True)
fp.set_preference("browser.download.manager.showWhenStarting",False)

browser = webdriver.Firefox(firefox_binary=binary, firefox_profile=fp, executable_path=gecko)

硒错误:

Traceback (most recent call last):
  File "weeklyData_v5.py", line 18, in <module>
IOError: [Errno 2] No such file or directory: 'inputArguments.txt'
Traceback (most recent call last):
  File "weeklyData_v5.py", line 18, in <module>
IOError: [Errno 2] No such file or directory: 'inputArguments.txt'

另外两个错误示例:

  File "selenium\webdriver\firefox\webdriver.pyc", line 144, in __init__
  File "selenium\webdriver\common\service.pyc", line 81, in start
selenium.common.exceptions.WebDriverException: Message: 'geckodriver32.exe' executable needs to be in PATH. 

--

browser = webdriver.Firefox(firefox_binary=binary, firefox_profile=fp, executable_path=gecko)
  File "selenium\webdriver\firefox\webdriver.pyc", line 144, in __init__
  File "selenium\webdriver\common\service.pyc", line 74, in start
  File "subprocess.pyc", line 382, in __init__

  File "subprocess.pyc", line 515, in _get_handles

  File "subprocess.pyc", line 566, in _make_inheritable

WindowsError: [Error 6] The handle is invalid

【问题讨论】:

    标签: python selenium py2exe


    【解决方案1】:

    你的错误是这样想。是脚本的路径。它不是。它是相对于当前工作目录的路径。这可以是可执行文件所在的目录,然后事情可能会起作用。但它可以是完全不同的地方。

    您需要改为使用赋予程序的第一个命令行参数,即可执行文件。

    import os
    import sys
    BASE = os.path.dirname(sys.argv[0])
    

    【讨论】:

    • 谢谢。我做了这个改变,代码仍然有效。但是,当我运行可执行文件(来自 py2exe)时,出现错误“NameError: name '__ file __' is not defined”
    • @dsauce 看我更新的答案,py2exe 有专长。
    • 谢谢。这使得代码(作为 exe)有时可以工作,但有时我仍然会出错(例如找不到壁虎驱动程序)或“WindowsError:[错误 6] 句柄无效”。用更多错误示例更新了问题文本。
    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 2013-08-16
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多