V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
frmongo
V2EX  ›  问与答

Python 多进程问题咨询

  •  
  •   frmongo · May 6, 2020 · 1440 views
    This topic created in 2181 days ago, the information mentioned may be changed or developed.

    各位帅哥,我写了个脚本,作用是,持续地把串口的打印保存到一个文本里,然后可以自定义时间后停止。 代码如下,但是停止后,似乎因为没有保存,导致文本是空的,怎么写可以实现这个目的呢。

    import serial
    from multiprocessing import Process as process
    from time import sleep
    import sys
    
    def get_print(comport):
        ser = serial.Serial(comport,baudrate=115200,bytesize=8,parity='N',stopbits=1,timeout=1)
        with open('m3.txt','w',encoding="gb18030") as f:
            while 1:
                if ser.inWaiting():
                    x=ser.read(150)
                    lll = x.decode('gb18030','replace')
                    f.write(lll)
    
    
    if __name__ == '__main__':
        p1 = process(target=get_print, args=('com7',))
        p1.daemon=True
        p1.start()
        sleep(10)
        sys.exit('ok')
    
    6 replies    2020-05-06 19:24:51 +08:00
    Hstar
        1
    Hstar  
       May 6, 2020
    两种思路,其实没区别都是在 get_print 函数的 while 1 这个地方做文章
    1. 把 10 这个变量传进 get_print 函数,在 while 1 这个地方一直比对是否超过 10 秒了
    2. 看一下多线程 /进程的 Event 对象,初始化一个锁传进 get_print 函数,while 1 这个地方观察锁是否还在,十秒后把这个锁 clear 掉,让 get_print 停住
    无论怎么样 sys.exit('ok')都要换成 p1.join()
    renmu
        2
    renmu  
       May 6, 2020 via Android
    提醒一下多进程文件写入会导致混乱,这件事应该用单进程就能用,你用 sleep 直接把主进场堵死了,四舍五入还是只有一个进程在工作
    BingoXuan
        3
    BingoXuan  
       May 6, 2020
    用 Thread 类启动线程,加一个实例变量控制线程运行,时间到了就修改变量值停止线程并保存数据
    Kilerd
        4
    Kilerd  
       May 6, 2020
    Python 只能单线程(
    Vegetable
        5
    Vegetable  
       May 6, 2020
    https://www.runoob.com/python/file-flush.html

    由于你只有一个 thread 在写,只需要 flush 操作就行了。
    crella
        6
    crella  
       May 6, 2020 via Android
    while 判断全局变量,如果 false,则关闭文件 io,同时 break
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   846 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 21:21 · PVG 05:21 · LAX 14:21 · JFK 17:21
    ♥ Do have faith in what you're doing.