Reputation: 4152
Code is working perfectly but How can I quit a script which is using a loop? Is there any method because Ctrl+C
did not work. I do not have Break/Pause
button in my keyboard so I could use it.
import pandas as pd
import os
from os import listdir
from os.path import isfile, join
from PIL import Image
import requests
from io import BytesIO
import argparse
arg_parser = argparse.ArgumentParser(allow_abbrev=True, description='Download images from url in a directory',)
arg_parser.add_argument('-d','--DIR',required=True,
help='Directory name where images will be saved')
arg_parser.add_argument('-c','--CSV',required=True,
help='CSV file name which contains the URLs')
arg_parser.add_argument('-i','--index',type=int,
help='Index number of column which contain the urls')
arg_parser.add_argument('-e','--end',type=int,
help='How many images to download')
args = vars(arg_parser.parse_args())
def load_save_image_from_url(url,OUT_DIR,img_name):
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img_format = url.split('.')[-1]
img_name = img_name+'.'+img_format
img.save(OUT_DIR+img_name)
return None
csv = args['CSV']
DIR = args['DIR']
ind = 0
if args.get('index'):
ind = args['index']
df = pd.read_csv(csv) # read csv
indices = [int(f.split('.')[0]) for f in listdir(DIR) if isfile(join(DIR, f))] # get existing images
print(f'There are already {len(indices)} images present in the directory -{DIR}-')
start = 0
if len(indices):
start = max(indices)+1 # set strating index
end = 5000 # next n numbers of images to download
if args.get('end'):
end = args['end']
print(f'Downloaded a total of {len(indices)} images upto index: {start-1}. Downloading the next {end} images from -{csv}-')
count = 0
for i in range(start, start+end):
if count%250==0:
print(f"Total {start+count-1} images downloaded in directory. {end-count} remaining from the current defined")
url = df.iloc[i,ind]
try:
load_save_image_from_url(url,DIR,str(i))
count+=1
except:
print(f'Error Occured at index: {i}')
pass
I just want to quit the program while running. If I have to quit it, I have to close the terminal but I don't think this is the proper way. How could I quit it "properly" without closing the terminal?
Upvotes: 3
Views: 331
Reputation: 366
You can use the KeyboardInterrupt to exit your application as follows:
try:
### code that prevented the exit goes here
except (KeyboardInterrupt, SystemExit):
print("Forced exit")
raise
Then you can normally exit with Ctrl+C
Upvotes: 3