3

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?

10
  • Try ctrl+z. Then to fully close it, run sudo pkill python Commented Jul 31, 2020 at 3:06
  • Why load_save_image_from_url function returns None? Commented Jul 31, 2020 at 3:08
  • If you will use this script regularly, you can try putting the main code in a background thread Commented Jul 31, 2020 at 3:08
  • 1
    Try except KeyboardInterrupt: Commented Jul 31, 2020 at 3:09
  • 1
    Don't use a bare except The bare except catches all exceptions, and you merely pass after that. So instead of except: ... use except Exception as e: at least... Commented Jul 31, 2020 at 3:15

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

So what if I want to just say that there has been an error but want to quit if a keyboard error has occured?
you can use multiple except statement for the same try block where each except catches certain exceptions
Shouldn't I be using sys.exit(0) or something like that? I mean how would my program quit from memory?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.