【问题标题】:python-shell problem with sync inside javascriptjavascript中同步的python-shell问题
【发布时间】:2022-09-27 21:43:43
【问题描述】:

我在用着python-shell运行一个Python代码在 a 中返回一些消息JavaScript 环境,但消息来了不同步.这第一条消息返回正确的时刻, 但是之后所有其他消息出来一起最后,不一一。

当我单独运行test.py 时,消息以正确的方式出现,这可能意味着我的python 代码没有问题。尽管所有其他消息都记录在一起,但它们在 python 代码中执行的时间是正确的,每条消息中的time: 可以看到什么。

但是在我的浏览器环境中发生的是消息<2>FIRST TEST 首先记录,然后<3>TEST<4>MORE TEST 在10 秒后一起记录。

这是我的python代码test.py

import sys
import time
import threading

def test():
    start = time.time()
    end1 = time.time()
    print(\"<2>FIRST TEST time: {}\".format(end1 - start))

    time.sleep(5)
    end2 = time.time()
    print(\"<3>TEST time: {}\".format(end2 - start))

    time.sleep(5)
    end3 = time.time()
    print(\"<4>MORE TEST time: {}\".format(end3 - start))

x = threading.Thread(target=test)
x.start()
sys.stdout.flush()

这是我的 JavaScript 代码execPyShell.ts

const exec: () => void = () => {
    console.log(\'Start\')
    let pyshell = new PythonShell(\'./engine/test.py\');
    let newLogs: string[] = [];

    pyshell.on(\'message\', function(message: string) {
        console.log(message);
    })

    pyshell.end(function (err: any) {
    if (err){
        throw err;
    };
        console.log(\'Finished\');
    });
}

    标签: javascript python python-multithreading


    【解决方案1】:

    解决了!我忘了我必须添加

    sys.stdout.flush()
    

    在每次调用 print() 以强制它刷新缓冲区之后。

    【讨论】:

      猜你喜欢
      • 2014-10-29
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      相关资源
      最近更新 更多