gpt4 book ai didi

python - .pyw 和 pythonw 不能在 Windows 7 下运行

转载 作者:IT老高 更新时间:2023-10-28 20:46:37 27 4
gpt4 key购买 nike

运行一个简单的 .py 或 .pyw python 文件会导致 python.exe显示在任务管理器下。

python myApp.py
python myApp.pyw

但是,当我们尝试在不使用控制台的情况下运行它时,脚本似乎没有运行, python.exe 也没有运行。或 pythonw.exe出现在任务管理器下
pythonw myApp.pyw
pythonw myApp.py

我们如何解决问题?系统运行 Python 2.7.8 x64。

最佳答案

tl;博士

  • 故障排除 , 使用 输出重定向调用时:
    pythonw myApp.py 1>stdout.txt 2>stderr.txt

  • 这将捕获 stdout 输出,例如来自 print() , 在文件 stdout.txt 中和 stderr 输出(例如来自未处理的异常),在文件 stderr.txt 中;从 PowerShell,使用 cmd /c pythonw myApp.py 1>stdout.txt 2>stderr.txt )。
    请注意,重定向标准输出的行为实际上可能会使您的脚本再次工作,如果这是导致 pythonw 失败的唯一原因的话。是使用 print (在 Python 2.x 中 - 见下文)。
    警告 : 这种输出重定向技术在调用 *.pyw 时似乎不起作用直接脚本(而不是通过将脚本文件路径传递给 pythonw.exe )。如果您知道原因和/或它是否适合您,请告诉我。
  • 修复您的脚本 :

  • 将以下内容放在任何 Python 2.x 或 3.x 脚本的顶部 你想要的 运行 pythonw.exe :
    import sys, os
    if sys.executable.endswith("pythonw.exe"):
    sys.stdout = open(os.devnull, "w");
    sys.stderr = open(os.path.join(os.getenv("TEMP"), "stderr-"+os.path.basename(sys.argv[0])), "w")

    当使用 pythonw.exe 运行脚本时,这可以确保以下内容:
  • print()调用和显式调用 sys.stdout()被有效地忽略(无操作)。
  • Stderr 输出,包括来自未处理的致命异常,被发送到文件%TEMP%\stderr-<scriptFileName> ; %TEMP%是一个标准的 Windows 环境变量,指向当前用户的临时文件文件夹。

  • 换句话说:有了上面的代码, 检查文件 %TEMP%\stderr-<scriptFileName>在您的脚本在使用 pythonw.exe 调用时静默失败后 .

    有关解释,请继续阅读。

    在 Windows 上, pythonw.exe用于启动 GUI/no-UI-at-all 脚本,这意味着
    标准输入和输出流 - sys.stdin , sys.stdout , sys.stderr不可用。


    这有 两个讨厌的副作用 :
  • 使用 print() - 目标 sys.stdout默认 - 在 Python 2.x 中导致异常 .
  • 此问题已在 Python 3.x 中修复。
  • 任何未处理的异常 - 包括由 print() 触发的一个在 2.x 中 - 导致脚本 静默中止 .
  • 异常错误消息转至 sys.stderr默认情况下,这在这种情况下是不可用的。

  • 上面的代码通过以下方式解决了这些问题:
  • 将 stdout 输出发送到空设备,有效地忽略任何输出到 sys.stdout 的尝试- 无论是显式还是隐式通过 print() .
  • 将所有 stderr 输出发送到临时文件。


  • Python 2.x 和 Python 3.x 之间的差异:

    当使用 pythonw.exe 运行脚本时, sys.stdin , sys.stdout , 和 sys.stderr :
  • 在 Python 中 2.x : 有 无效的文件描述符
  • 尝试写入 sys.stdout 时的最终结果或 sys.stderr是以下异常:IOError: [Errno 9] Bad file descriptor
  • 陷阱:由于输出缓冲,这个异常可能不会出现,直到你输出,比如 4K 字节;您可以通过调用 pythonw.exe 立即激发它与 -u (对于无缓冲输出)。
  • print()盲目尝试sys.stdout (默认情况下),因此它迟早会引发此异常。
  • 在 Python 中 3.x :是 设置为 None
  • 这是 3.x print() 的补充函数在发现 sys.stdout 时执行无操作(什么都不做)是 None ,所以 print()默认情况下可以安全地使用语句 - 当使用 pythonw.exe 运行时,它们将被简单地忽略。
  • 但是,随之而来的是尝试使用 sys.stdout.write()sys.stderr.write()仍然导致异常。

  • here更多背景。

    关于python - .pyw 和 pythonw 不能在 Windows 7 下运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24835155/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com