Search code examples
pythonpython-2.7subprocessunzip

subprocess unzip with source file remove?


I'm using python subprocess to unzip a zip archive. My code is as below:

subprocess.Popen(['unzip', '{}.zip'.format(inputFile), '-d', output_directory])

Is there an unzip command to remove the zip source file after unzipping it? If no, how can I pipe an rm to the subprocess.Popen but to make sure it waits for the file to unzip first?

Thanks.


Solution

  • You could use && in the Shell, which will execute the second command only if the first was successful:

    import subprocess
    import os
    
    values = {'zipFile': '/tmp/simple-grid.zip', 'outDir': '/tmp/foo'}
    command = 'unzip {zipFile} -d {outDir} && rm {zipFile}'.format(**values)
    proc = subprocess.Popen(command, shell=True)
    _ = proc.communicate()
    
    print('Success' if proc.returncode == 0 else 'Error')
    

    Or, os.remove() if unzip succeeded:

    inputFile = values['zipFile']
    output_directory = values['outDir']
    
    proc = subprocess.Popen(
        ['unzip', '{}'.format(inputFile), '-d', output_directory]
    )
    _ = proc.communicate()  # communicate blocks!
    
    if proc.returncode == 0:
        os.remove(values['zipFile'])
    print('Success' if not os.path.exists(inputFile) else 'Error')