Knowing that Python has a zipfile module, (While knowing the free software for zip decompression and the standard zip decompression function for Windows) I decided to make a simple decompression tool with the following specifications.
--Drop the zip file into a DOS batch and unzip it
--Python on Windows cannot be dropped directly into a script (* .py)
--The output folder path is the full path of the zip file with the extension removed.
--Input: [Arbitrary folder] \ [Arbitrary name] .zip
--Output: [Arbitrary folder] \ [Arbitrary name]
--The DOS window will close immediately after the decompression process is completed normally.
--If the decompression process ends abnormally, the DOS window will display the exit code and wait for input.
Then I called it with the intention of C # ʻApplication.exit () I've been addicted to
sys.exit ()` for a few minutes, so make a note of it.
For the time being, I will show you the completed form first. It is assumed that Python is installed and Path is passed. The file name of each script is fixed, but anything is fine as long as it is consistent with the description in the DOS batch.
extract.bat
@echo off
cd /d "%~dp0"
::"Extract" in the same hierarchy as this batch.Premise that there is "py"
python extract.py -i "%~1"
if errorlevel 1 (
echo.Decompression failed.
echo.ExitCode:%errorlevel%
pause
)
extract.py
from argparse import ArgumentParser
import os
import sys
import zipfile
def main():
parser = ArgumentParser()
parser.add_argument("-i", "--input", default=False, help="Input Zip")
args = parser.parse_args()
filePath = args.input
if (not filePath):
sys.exit(1)
if (not os.path.isfile(filePath)):
sys.exit(2)
folderName = os.path.splitext(os.path.basename(filePath))[0]
outputPath = os.path.join(os.path.dirname(filePath), folderName)
try:
with zipfile.ZipFile(filePath) as zip:
zip.extractall(outputPath)
except:
sys.exit(3)
else:
sys.exit(0)
if (__name__ == "__main__"):
main()
To tell you the truth, I continued to be addicted to it without knowing the following. -[Python] sys.exit () just throws an exception
It's faster to look at the code to see how you got hooked.
Even at the time of normal termination, the exit code is now 3. .. ..
try:
with zipfile.ZipFile(filePath) as zip:
zip.extractall(outputPath)
sys.exit(0)
except:
sys.exit(3)
Even at the time of abnormal termination, the exit code became 0. .. ..
try:
with zipfile.ZipFile(filePath) as zip:
zip.extractall(outputPath)
except:
sys.exit(3)
finally:
sys.exit(0)
Thanks to my addiction, I understand how Python try-except-else-finally works.
Recommended Posts