python - 队列和线程: subprocess goes missing

标签 python multithreading video subprocess video-processing

早上好,

我正在编写一个 python 守护程序,需要将视频转换为 .mp4 格式。 为此,我计划通过 Subprocess 使用 Handbrake,但我得到的结果好坏参半:有时它有效,有时该过程甚至没有显示在顶部。

我不确定发生了什么事。我尝试了一些变体,例如使用 Shell=True,但问题仍然存在。

谢谢

#! /usr/bin/python
# -*- coding: utf-8 -*- 
import os, time, threading, psutil, resource, logging, subprocess as sp, sys
from Queue import Queue
from threading import Thread

SERVER_LOG=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'convertCentral.log')
logging.basicConfig(format='[%(asctime)s.%(msecs).03d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=SERVER_LOG, level=logging.INFO)

class QueueServer(object):

    current_video_queue = Queue(maxsize=0)
    N_WORKER_THREADS = 1
    counter = 0


    def __init__(self):
        print("[QueueServer] Initializing the video conversion queue")
        t = threading.Thread(target=self.monitor)
        t.start()


    ''' Alters the process' niceness in order to throtle the CPU usage '''
    def preexec_fn(self):
        pid = os.getpid()
        ps = psutil.Process(pid)
        ps.set_nice(10)
        resource.setrlimit(resource.RLIMIT_CPU, (1, 1))


    ''' Converts the video using Handbrake via subprocess'''
    def convertVideo(self, video):
        print("Now converting %s" % video)
        fileName, fileExtension = os.path.splitext(video)
        payload = "ulimit -t 360; nice -n 15 HandBrakeCLI -i %s -e x264 -q 15 -o %s.mp4" % (video, fileName)
        payload = payload.split(" ")

        # Fire in the hole
        pr = sp.Popen(payload, stdout=open('/dev/null', 'w'), stderr=sp.STDOUT)
        print("Fired.")
        pr.wait()

        self.counter = self.counter + 1
        print("Conversion's done. %d" % self.counter)


    ''' A worker thread '''
    def worker(self):
        while True:
            print("Getting one")
            item = self.current_video_queue.get()
            print("Firing conversion: %s" % item)
            self.convertVideo(item)
            self.current_video_queue.task_done()
            print("All done")


    def monitor(self):
        for i in range(self.N_WORKER_THREADS):
            print("Firing thread")
            t = Thread(target=self.worker)
            t.daemon = True
            t.start()


    ''' Adds a video to the video conversion queue '''
    def add(self, video):
        print("* Adding %s  to the queue" % video)
        self.current_video_queue.put(video)
        print("* Added %s  to the queue" % video)


q = QueueServer()
q.add('UNKNOWN_PARAMETER_VALUE.WMV')
#time.sleep(500)

这是我在日志中得到的内容:

Hal@ubuntu:~/Desktop/$ python threadedqueue.py
[QueueServer] Initializing the video conversion queue
Firing thread
* Adding UNKNOWN_PARAMETER_VALUE.WMV  to the queue
* Added UNKNOWN_PARAMETER_VALUE.WMV  to the queue
Getting one
Firing conversion: UNKNOWN_PARAMETER_VALUE.WMV
Now converting UNKNOWN_PARAMETER_VALUE.WMV

所以,我们可以看出子进程实际上在运行,但它只是神秘地死在那里...... 有什么想法可能导致此问题吗?

最佳答案

首先,您提供的有效负载可能不是您想要的。

在正常操作中,子进程不会将命令发送给 shell,而是启动名称位于 args[0] 的进程,并将所有其他参数直接传递给它。您正在做的是传递以下参数:

["-t", "360;", "nice", "-n", "15", "HandBrakeCLI", "-i", "someInput", "-e", "x264", "-q", "15", "-o", "someOutput.mp4"]

...非常困惑的 ulimit 进程。 相反,您想要的是使用 shell=True,并提供 args 作为字符串。这告诉 Popen 启动一个 shell 并将其全部转储为一行,而不是实际启动您所请求的进程。

payload = "ulimit -t 360; nice -n 15 HandBrakeCLI -i %s -e x264 -q 15 -o %s.mp4" % (video, fileName)
pr = sp.Popen(payload, shell=True, stdout=sp.DEVNULL, stderr=sp.STDOUT)
print('Started handbrake')
pr.wait()

如果您没有打印“Started handbrake”(已启动手刹),则可能是 Popen 出现了严重错误。调试它的一个好方法是获取有效负载,导入子进程并尝试在交互式控制台上使用 Popen 打开它。如果您被锁定在 Popen 调用中,则 ctrl-c 应该可以跟踪您卡在其中的位置,这可能反过来为您提供一些帮助。即使这对您来说毫无意义,也可能会帮助其他人了解发生了什么。

希望这对您有所帮助!

关于python - 队列和线程: subprocess goes missing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23130031/

相关文章:

multithreading - 如何可视化多线程进程?

video - Windows Media Foundation 使用 IMFTransform 将 mp4 电影帧解码为 2D 纹理

ios - 在 iPhone 设备上的 ionic 应用程序中播放视频时没有声音

javascript - django-allauth 未捕获的 ReferenceError

python - 如何将掩码应用于张量并保持其原始形状

python - Django 使用 AJAX 下载 Excel 文件

html - 如何显示具有循环视频背景的部分的文本?

Python:没有名为 suds 的模块

android - 如何在同一线程上继续执行 Firebase 任务

java - 停放正在使用的线程