简体   繁体   中英

Python break statement within try except block

How to put a break statement within try and except block, I want to print the Message `Invalid interface on the host123.

#!/usr/bin/python
# cat /proc/net/bonding/bond0

import sys
import re
import socket
import os

system_name = socket.gethostname()

def usage():
        print '''USAGE: %s [options] [bond_interface]

Options:
        --help, -h      This usage document

Arguments:
        bond_interface  The bonding interface to query, eg. 'bond0'. Default is 'bond0'.
''' % (sys.argv[0])
        sys.exit(1)

# Parse arguments
try:
        iface = sys.argv[1]
        if iface in ('--help', '-h'):
                usage()
except IndexError:
        iface = 'bond0'

# Grab the inf0z from /proc
try:
        bond = open("/proc/net/bonding/%s" % iface).read()

except IOError:
        print "ERROR: Invalid interface %s %s\n" % (iface, system_name)
        usage()

I tried to put the if condition as follows but gives SyntaxError: 'break' outside loop .

# Grab the inf0z from /proc
try:
        bond = open("/proc/net/bonding/%s" % iface).read()
        if not os.path.exists("bond"):
            break
except IOError:
        print "ERROR: Invalid interface %s %s\n" % (iface, system_name)
        usage()

However print statement works but also prints help section which i want to stop

ERROR: Invalid interface apc4502.nxdi.nl-cdc01.nxp.com bond0

USAGE:  [options] [bond_interface]

Options:
        --help, -h      This usage document

Arguments:
        bond_interface  The bonding interface to query, eg. 'bond0'. Default is 'bond0'.

any help would be appreciated.

Use argparse to parse your command-line arguments.

#!/usr/bin/python
# cat /proc/net/bonding/bond0

import sys
import socket
import os

import argparse

p = argparse.ArgumentParser()
p.add_argument('bond_interface', default='bond0')
args = p.parse_args()

system_name = socket.gethostname()

bond_name = os.path.join("/proc/net/bonding", args.bond_interface)

try:
    with open(bond_name) as f:
        bond =  f.read()
except IOError:
    print(f"ERROR: Problem reading from {bond_name} on {system_name}", file=sys.stderr)

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