Moved from os.system to subprocess.call
[youtube-dl] / youtube_dl / postprocessor / execafterdownload.py
1 from __future__ import unicode_literals
2 from .common import PostProcessor
3 from ..utils import PostProcessingError
4 import subprocess
5 import shlex
6
7
8 class ExecAfterDownloadPP(PostProcessor):
9     def __init__(self, downloader=None, verboseOutput=None, commandString=None):
10         self.verboseOutput = verboseOutput
11         self.commandString = commandString
12
13     def run(self, information):
14         self.targetFile = information['filepath'].replace('\'', '\'\\\'\'')  # Replace single quotes with '\''
15         self.commandList = shlex.split(self.commandString)
16         self.commandString = ''
17
18         # Replace all instances of '{}' with the file name and convert argument list to single string.
19         for index, arg in enumerate(self.commandList):
20             if(arg == '{}'):
21                 self.commandString += '\'' + self.targetFile + '\' '
22             else:
23                 self.commandString += arg + ' '
24
25         if self.targetFile not in self.commandString:  # Assume user wants the file appended to the end of the command if no {}'s were given.
26             self.commandString += '\'' + self.targetFile + '\''
27
28         print("[exec] Executing command: " + self.commandString)
29         self.retCode = subprocess.call(self.commandString, shell=True)
30         if(self.retCode < 0):
31             print("[exec] WARNING: Command exited with a negative return code, the process was killed externally. Your command may not of completed succesfully!")
32         elif(self.verboseOutput):
33             print("[exec] Command exited with return code: " + str(self.retCode))
34
35         return None, information  # by default, keep file and do nothing
36
37
38 class PostProcessingExecError(PostProcessingError):
39     pass