Python Popen()正在阻塞

2024-05-16 01:46:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个小python脚本来自动创建Jekyll博客,但是popen()似乎会阻塞,而不是异步调用

预期的行为是:

  1. 异步启动jekyll serve --livereload
  2. 异步启动firefox-esr http://127.0.0.1:4000并等待它(或同步启动,这与我的用例无关)
  3. 在firefox终止后,也终止Jekyll
jekyll = subprocess.Popen(['jekyll', 'serve', '--livereload'])
print('This never gets displayed')
time.sleep(3)
firefox = subprocess.Popen(['firefox-esr', 'http://127.0.0.1:4000'])
firefox.wait()
jekyll.terminate()

但这只会启动Jekyll并将其标准输出到终端

这个问题只出现在杰基尔身上ping或我尝试过的任何其他命令/程序工作正常

你知道我做错了什么吗


Tags: 脚本httpfirefoxthis用例subprocessprintpopen
1条回答
网友
1楼 · 发布于 2024-05-16 01:46:16

如果您在Linux上,您可以为它创建一个简单的bash脚本

#!/bin/bash

jekyll serve  livereload & 
sleep 5
firefox-esr http://127.0.0.1:4000 &>/dev/null


pid=$(pgrep firefox-esr)

while :
do
    sleep 5
    if [ -z  "$pid" ]
    then
        pkill ruby 2>/dev/null
        echo "Killed jekyll"
        break
    fi
done

使用授予此文件执行权限

chmod +x filename.sh

然后使用运行此bash脚本

./filename.sh &

这将使脚本在后台运行

相关问题 更多 >