2017-07-11 2 views
1

J'ai un code Python 3 censé enregistrer de la vidéo. Malheureusement, je ne le veux pas en .h264, j'en ai besoin pour convertir en .mp4. En utilisant d'autres threads StackOverflow comme un modèle (en particulier this un), je pensais que la façon la plus simple de faire cela aurait été d'utiliser subprocess.Popen pour insérer MP4Box -add filename.h264 filename.mp4 dans le terminal et de le faire pour moi automatiquement. Malheureusement, le script Python ne fait rien et je ne reçois aucun message d'erreur, donc je ne sais pas ce qui ne va pas. Le fichier .h264 apparaît dans le dossier que je veux, si je mets manuellement la commande dans le terminal, le fichier .mp4 apparaît, mais quand je le laisse tourner, rien ne se passe. Le reste du script fonctionne comme un charme. Le code est ici:(python 3) Conversion automatique de .h264 en .mp4

#!/usr/bin/python 

from gpiozero import MotionSensor 
from gpiozero import Motor 
from picamera import PiCamera 
import subprocess 
import os.path 
import shlex 
import datetime as dt 
from time import sleep 

camera = PiCamera() 
pir = MotionSensor(4, 1, 100, .6, False) 
motor = Motor(3,14) #first number is forwards, second is backwards 
startupTime = 1 
recordingTime = 1 
collectionTime = 3 
resetTime = 30 



while True: 
    sleep(startupTime) #delay a bit so installation can take place 

    #wait for motion, then move the motor back and forth 
    pir.wait_for_motion() 
    print("Motion Detected") 
    #moves motor forward for 3 seconds at 25% speed 
    motor.forward(.25) 
    print("Strip Extending") 
    sleep(3) 
    motor.stop() 
    #leaves strip out for given amount of time 
    print("Collecting Sample") 
    sleep(collectionTime) 
    #moves motor backward for 3 seconds at 50% speed 
    motor.backward(.5) 
    print("Strip Retracting") 
    sleep(3) 
    motor.stop() 

    #Prep file for correct saving 
    filename = dt.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264") #saves file as a date 
    save_path= "/home/pi/ANALYSIS" 
    completed_video= os.path.join(save_path, filename) 

    #Start recording 
    camera.start_recording(completed_video) #starts recording and saves it as filename 
    print("Camera Recording") 
    camera.annotate_text = dt.datetime . now() . strftime("%Y-%m-%d_%H.%M.%S") 
    start=dt.datetime.now() 

    #Keep recording until time runs out, annotate to make sure we have reference frame 
    while (dt.datetime.now() - start).seconds < recordingTime: 
     camera.annotate_text = dt.datetime.now(). strftime("%Y-%m-%d_%H.%M.%S") 
     camera.wait_recording(.2) 
    camera.stop_recording() 

    #Conversion to usable file format 
    print("Camera finished recording... Beginning Analysis") 
    from subprocess import CalledProcessError 
    command = shlex.split("MP4Box -add {} {}.mp4".format(completed_video, os.path.splitext(filename)[0])) 
    try: 
     output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) 
    except CalledProcessError as e: 
     print('FAIL:\ncmd:{}\noutput:{}'.format(e.cmd, e.output)) 

    #starts detecting again after given time 
    sleep(resetTime) 
    print("Ready for next sample") 

>Traceback (most recent call last): 
> 
    File "/home/pi/Detector.py", line 62, in <module> output = 
     subprocess.check_output(command, stderr=subprocess.STDOUT) 
    File "/usr/lib/python3.4/subprocess.py", line 620, in check_output raise 
     CalledProcessError(retcode, process.args, output=output) 
     subprocess.CalledProcessError: 
     Command '['MP4Box', '-add', '2017-07-11_15.34.49.h264.h264', '2017-07-11_15.34.49.h264.mp4']' 
> 
Returned non-zero exit status 1" 

Répondre

1

Comment: 2017-07-11_15.34.49.h264.h264

Votre Filepath/Nom du fichier est erroné, le changement à ce qui suit:

Note: The .mp4 is saved in to the Current Directory the Subprocess is executed,
the Directory the Python Script is started. This could be different as the .h264 are saved!
Think about to change that also to be a absolute Path.

command = "MP4Box -add {} {}.mp4".format(completed_video, os.path.splitext(filename)[0]) 
try: 
    output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) 
except subprocess.CalledProcessError as e: 
    print('FAIL:\ncmd:{}\noutput:{}'.format(e.cmd, e.output)) 

os.remove(path, *, dir_fd=None)

Remove (delete) the file path.


Question: I don't get any error messages, so I don't know what's going wrong.

Effectuez les opérations suivantes:
Pour capturer aussi l'erreur-type dans le résultat, utilisez stderr=subprocess.STDOUT:

command = shlex.split("MP4Box -add {f}.h264 {f}.mp4".format(f=filename)) 
output = subprocess.check_output(command, stderr=subprocess.STDOUT) 
print(output) 

Je suppose que vous avez besoin shell=True que vous ne donnez pas un FULLPATH à MP4Box donc un environnement Shell est nécessaire pour trouver MP4Box.

+0

Il dit "retraçage (le plus récent appel dernier): Fichier "/home/pi/Detector.py", ligne 62, en sortie = subprocess.check_output (commande, stderr = subprocess.STDOUT) fichier" /usr/lib/python3.4/subprocess.py ", ligne 620, dans check_output raise CalledProcessError (retcode, process.args, sortie = sortie) subprocess.CalledProcessError: Commande '[' MP4Box ',' -add ', '2017-07-11_15.34.49.h264.h264', '2017-07-11_15.34.49.h264.mp4'] 'a renvoyé l'état de sortie non nul 1 "ajouterais-je shell = True après le (f = nom de fichier) et après une virgule aussi? – NeonCop

+0

Ok, je l'ai édité avec l'erreur la plus récente et mon script .py mis à jour. J'ai également essayé l'ancien code en utilisant un nom de fichier différent de sorte que le .h264 n'a pas répété, mais à aucun voile. – NeonCop

+0

Il est écrit "Aucun nom de module 'CalledProcessError'", dois-je l'importer d'un autre module? – NeonCop