我有一个有效的 bash 脚本,可以根据终端上按下的不同键在 vlc 中打开不同的视频。当视频正在播放但我按另一个键时,当前视频会停止,并开始再现新视频。但因为我不想显示终端,所以我创建了一个使用 subprocess 库打开 bash 脚本的 Python 脚本。它显示一个用 pygame 制作的界面(目前它只显示黑屏,我只是需要它),它还处理 keydown 事件,然后将其发送到在后台运行的 bash 脚本(该脚本打开 vlc 并重现视频)。每当我尝试以这种方式打开视频时,vlc 都会闪烁然后消失,根本不再现任何内容。其他选项(比如按 k 关闭程序)工作得很好,所以它一定是 vlc 的东西
#!/bin/bash
kill_vlc () {
# Check if VLC is running and kill it
if pgrep -x "vlc" > /dev/null; then
pkill -x "vlc"
# Adding a small sleep to ensure VLC fully closes before trying to open a new instance.
sleep 1
fi
}
declare -A videos
# load video mappings from file
# the file has this form:
# 3=/path/to/video/video3.mp4
# 2=/path/to/video/video2.mp4
# 1=/path/to/video/video1.mp4
while IFS="=" read -r key path; do
videos["$key"]="$path"
done < <(grep '=' video_mappings2.txt)
# echo the names
for key in "${!videos[@]}"; do
video_path="${videos[$key]}"
video_name="$(basename "$video_path")" # extract filename
video_name_woutext="${video_name%.*}" # remove extension
echo "> Key: $key, Video: $video_name_woutext"
done
echo ""
echo "> Press a key to play a video (options: ${!videos[@]})"
echo "> Press 'q' to quit the video"
echo "> Press 'k' to close the program"
# main loop
while true; do
read -s -n 1 key
# Close the script
if [[ $key == "k" ]]; then
echo "> Closing..."
# Check if VLC is running and kill it
kill_vlc
break
fi
# Close the video
if [[ $key == "q" ]]; then
# Check if VLC is running and kill it
kill_vlc
fi
# Check if VLC is running and kill it
kill_vlc
# Check if the key is in the videos array
if [[ ${videos[$key]} ]]; then
vlc ${videos[$key]} --play-and-exit &
fi
done
import pygame
import subprocess
import os
import time
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
# Start the Bash script as a subprocess
bash_process = subprocess.Popen(["./video_player.sh"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)
# Function to display the still image
def display_still_image():
screen.fill((0, 0, 0))
pygame.display.flip()
running = True
display_still_image()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
key_pressed = chr(event.key)
print(key_pressed)
# Send the key to the Bash script
bash_process.stdin.write(key_pressed + "\n")
bash_process.stdin.flush()
# Check if the Bash script has finished
if bash_process.poll() is not None:
break
# Redraw the still image
display_still_image()
# Control frame rate
clock.tick(30)
# Close the subprocess
bash_process.stdin.close()
bash_process.stdout.close()
bash_process.stderr.close()
bash_process.terminate()
# Quit pygame
pygame.quit()
我还从 WSL 和 Raspberry OS 运行 python 脚本,也发生了同样的问题。 我尝试了另一个视频播放器(mpv),问题仍然存在。
免责声明:没有足够的声誉来发表评论,因此尝试回答
我认为你的问题出在 bash 脚本的第 63 行,它会在每次按键时杀死 vlc。
# Check if VLC is running and kill it
kill_vlc
如果你真的想继续这个过于复杂的结构,我会首先确保 bash 脚本在集成到 python 中之前正确运行。