Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在程序端关闭python进程_Python 3.x_Pyserial - Fatal编程技术网

Python 3.x 如何在程序端关闭python进程

Python 3.x 如何在程序端关闭python进程,python-3.x,pyserial,Python 3.x,Pyserial,我无法在程序结束时关闭在进程中正常运行的串行连接。(在windows/VSCode和Ctrl-C上) 我收到一条错误消息,大多数情况下,端口在程序的下一次启动时已经打开 我必须先完成运行过程吗 class serialOne(Process): def __init__(self, serial_port, debug, baudrate=57600, timeout=1): ... def terminate(self): print("close p

我无法在程序结束时关闭在进程中正常运行的串行连接。(在windows/VSCode和Ctrl-C上)

我收到一条错误消息,大多数情况下,端口在程序的下一次启动时已经打开

我必须先完成运行过程吗

class serialOne(Process):
    def __init__(self, serial_port, debug, baudrate=57600, timeout=1):
    ...

    def terminate(self):
        print("close ports")
        self.active = False
        self.ser.close()

    def run(self):
        while self.active:
            self.initCom()
            self.readCom()
            time.sleep(0.005)

    def main():
        global processList
        global debug

        while True:
            if debug == True:
                print("main")
            time.sleep(1.0)

        for process in processList:
            process.terminate()
我的主要观点是:

def main():
    global processList
    global debug

    while True:
        if debug == True:
            print("main") # actually doing nothing
        time.sleep(1.0)

    for process in processList:
        process.terminate()
这是错误消息:

Process serialOne-1:
Traceback (most recent call last):
  File "C:\Users\dgapp\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\process.py", line 297, in _bootstrap
    self.run()
Traceback (most recent call last):
  File "e:\_python\rfid_jacky\simple_multiprocess_rfid_02.py", line 129, in run
    time.sleep(0.005)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\ptvsd_launcher.py", line 45, in <module>
KeyboardInterrupt
    main(ptvsdArgs)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\__main__.py", line 265, in main
    wait=args.wait)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\__main__.py", line 258, in handle_args
    debug_main(addr, name, kind, *extra, **kwargs)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_local.py", line 45, in debug_main
    run_file(address, name, *extra, **kwargs)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_local.py", line 79, in run_file
    run(argv, addr, **kwargs)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_local.py", line 140, in _run
    _pydevd.main()
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\pydevd.py", line 1925, in main
    debugger.connect(host, port)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\pydevd.py", line 1283, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\pydevd.py", line 1290, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "c:\Users\dgapp\.vscode\extensions\ms-python.python-2018.12.1\pythonFiles\lib\python\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "e:\_python\rfid_jacky\simple_multiprocess_rfid_02.py", line 161, in <module>
    main()
  File "e:\_python\rfid_jacky\simple_multiprocess_rfid_02.py", line 140, in main
    time.sleep(1.0)
KeyboardInterrupt
Process serialOne-1:
回溯(最近一次呼叫最后一次):
文件“C:\Users\dgapp\AppData\Local\Programs\Python\Python37-32\lib\multiprocessing\process.py”,第297行,在_bootstrap中
self.run()
回溯(最近一次呼叫最后一次):
文件“e:\\u python\rfid\u jacky\simple\u multiprocess\u rfid\u 02.py”,第129行,正在运行
睡眠时间(0.005)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\ptvsd_launcher.py”,第45行,在
键盘中断
干管(ptvsdArgs)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\ uuuuuu main_uuuu.py”,第265行,在main中
wait=args.wait)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\ uuuuu main\uuuuuu.py”,第258行,在句柄参数中
debug_main(地址、名称、种类、*extra、**kwargs)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\ u local.py”,第45行,在debug\ u main中
运行文件(地址、名称、*extra、**kwargs)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\ u local.py”,第79行,在运行文件中
运行(argv,addr,**kwargs)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\ u local.py”,第140行,正在运行
_pydevd.main()
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\u vendored\pydevd\pydevd.py”,主文件第1925行
调试器.connect(主机、端口)
运行文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\u vendored\pydevd\pydevd.py”,第1283行
返回self.\u exec(是模块、入口点、模块名称、文件、全局、局部)
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\u vendored\pydevd\pydevd.py”,第1290行,在_exec中
pydev_imports.execfile(文件、全局、局部)#执行脚本
文件“c:\Users\dgapp\.vscode\extensions\ms python.python-2018.12.1\pythonFiles\lib\python\ptvsd\\u vendored\pydevd\\u pydev\u imps\\u pydev\u execfile.py”,execfile中第25行
exec(编译(内容+“\n”,文件,'exec'),全局,loc)
文件“e:\\u python\rfid\u jacky\simple\u multiprocess\u rfid\u 02.py”,第161行,在
main()
文件“e:\\u python\rfid\u jacky\simple\u multiprocess\u rfid\u 02.py”,第140行,在main中
时间。睡眠(1.0)
键盘中断

当您按下
Ctrl+C
时,将引发
键盘中断
异常,并中断无限睡眠循环。但是,由于您没有捕获此异常,因此此循环之后的代码(使用
process.terminate()
)永远不会被调用,这可能会导致您的问题

所以你有几个选择:

  • 捕捉
    键盘中断
    ,并使用该中断退出inifite循环:

    def main():
        global processList
        global debug
    
        try:
            while True:
                if debug == True:
                    print("main") # actually doing nothing
                time.sleep(1.0)
        except KeyboardInterrupt:
            pass
    
        for process in processList:
            process.terminate()
    
    这很简单,可读性也很强

  • 注册将在程序退出时运行的退出处理程序:

    import atexit
    
    @atexit.register
    def shutdown():
        global processList
    
        for process in processList:
            process.terminate()
    
    def main():
        global debug
    
        while True:
            if debug == True:
                print("main") # actually doing nothing
            time.sleep(1.0)
    
    哪一个更可靠,因为即使进程被另一个信号终止,它也能工作

当用户点击中断键时,会发生此错误

一个简单的解决方案是捕获异常:

while True:
    if debug == True:
        print("main") # actually doing nothing

    try:
        # do your things
    except KeyboardInterrupt:
        print("program was interrupted by user")
        break
您还可以使用
finally
关键字正确结束您的程序:

try:
    while True:
        # do your things    
except KeyboardInterrupt:
    print("program was interrupted by user")
    break
finally:
    close()  # this will always happen, even if an exception was raised