简体   繁体   中英

Program continues to execute after exit

After reading in an ip address from the user I want to exit out if not valid. It seems to continue executing the code in the function before exiting. I would like it to exit immediately. I have even tried using quit() and exit() in the expection but all had the same result.

Function:

def f_validate_args(test_args):
 try:
  socket.inet_aton(test_args.server)
 except socket.error as SE:
  raise SystemExit(SE)

 print 'Everything is OK!'

Main:

validation = f_validate_args(io_args)

print(io_args)

Running program with an Invalid IP:

Everything is OK
illegal IP address string passed to inet_aton

Running program with a Valid IP:

Everything is OK!
Namespace(...)

You can try os.system package, to kill from bash:

import os

def f_validate_args(test_args):
 try:
  socket.inet_aton(test_args.server)
 except socket.error as SE:
  os.system('pkill your_program_name')
  raise SystemExit(SE)

There may be resources (socket related) that prevent the program to exit cleanly.

Maybe dirty but sure to work: call os._exit . It calls low-level exit without using the exception mechanism that sys.exit uses.

def f_validate_args(test_args):
 try:
  socket.inet_aton(test_args.server)
 except socket.error as SE:
  print(str(SE))
  os._exit(1)

 print('Everything is OK!')

Of course, python doesn't have a chance to exit gracefully. Do this only if you can't do otherwise.

When an invalid IP is provided, the function will raise an OSError. So you will need to catch it with

def f_validate_args(test_args):
 try:
  socket.inet_aton(test_args.server)
 except OSError:
  # your error handling here
 except socket.error as SE:
  raise SystemExit(SE)

 print 'Everything is OK!'

Source: https://docs.python.org/3/library/socket.html#socket.inet_aton

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM