简体   繁体   English

使用JavaScript延时执行Python脚本

[英]Execute Python script with time delay using JavaScript

I wanted to execute a Python script through a JavaScript file because I would like to print results from a python script into an html page. 我想通过JavaScript文件执行Python脚本,因为我想将python脚本的结果打印到html页面中。 I started by looking into the python-shell module. 我从研究python-shell模块开始。 I followed this tutorial: 我遵循了本教程:

http://ourcodeworld.com/articles/read/286/how-to-execute-a-python-script-and-retrieve-output-data-and-errors-in-node-js http://ourcodeworld.com/articles/read/286/how-to-execute-a-python-script-and-retrieve-output-data-and-errors-in-node-js

I was successfully able to follow the tutorial and everything worked correctly. 我成功地遵循了该教程,并且一切正常。

However, I would now like to print out some numbers in the console with a time delay. 但是,我现在想在控制台中打印一些数字,但要有一定的时间延迟。 My Python script contains the following code: 我的Python脚本包含以下代码:

while True:
    print(random.randint(1,101))
    time.sleep(10)

When I run my JavaScript code, nothing happens. 当我运行我的JavaScript代码时,什么也没有发生。 I did some debugging and removed the time.sleep() statement and it works. 我进行了一些调试,并删除了time.sleep()语句,它可以正常工作。

What is the correct way to do this? 正确的方法是什么? Why does this work when I remove time.sleep() ? 为什么在删除time.sleep()时此方法起作用?

You need to flush the standard output stream in your python script after printing. 打印后,您需要在python脚本中刷新标准输出流。

import sys

while True:
    print(random.randint(1,101))
    sys.stdout.flush()
    time.sleep(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM