Home > Mobile >  subprocess unzip with source file remove?
subprocess unzip with source file remove?

Time:11-17

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.

CodePudding user response:

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')
  • Related