Search code examples
pythonpython-3.xubuntuhandbrake

HandbrakeCLI on Ubuntu with Python Errors with File Not Found


I'm trying to write a program in python3 that uses handbrakecli on my ubuntu machine to recode some video.

I'm missing something stupid but I cannot for the life of me figure this out, and I've been at it for countless hours.

Here's the code:

def convertvideo(input_file):
    hb_args = (" -i " + input_file + " -o " + handbraketempspace + " --preset-import-file "+handbrake_json_file_location + " -Z " + handbrake_profile_name)
    print (hb_args) # for debug only
    subprocess.Popen(handbrake + hb_args)
    return()

and no matter how I rearrange the " I get one of two errors, either handbrake says file not found or it cannot find my preset.

This exact command works perfectly from the command line.

Here's the specific error:

Traceback (most recent call last):
  File "SubProcessing.py", line 161, in <module>
    finalvideo = convertvideo(sys.argv[2])
  File "SubProcessing.py", line 82, in convertvideo
    subprocess.Popen(handbrake + hb_args)
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: "/usr/bin/HandBrakeCLI -i /root/Alone-S02E01-Once_More_Unto_the_Breach_HDTV-720p.mkv -o /root/tmp/tempvideo.mkv --preset-import-file /mnt/media/PlexTestFiles/handbrake_presets.json -Z 'h.265_Hardware'"

Thanks in advance for your help. Again, I'm not a python coder but I didn't think this would be this hard.


Solution

  • You need to call subprocess.Popen with the arguments in an array, not a string. In your case the relevant section would be:

    subprocess.Popen([handbrake, "-i", input_file, "-o", handbraketempspace, "--preset-import-file", handbrake_json_file_location, "-Z", handbrake_profile_name])
    

    Alternatively, you could specify shell=True to subprocess.Popen, but that starts a shell unnecessarily so it's best not to use it.