-2

So, this is the code I've got difficulties with:

import optarse
import subprocess

def get_arguments():
    parser = optparse.OptionParser()
    parser.add_option("-i", dest="interface")
    parser.add_option("-m", dest="new_mac")
    (options, arguments) = parser.parse_args()

def change_mac(interface, new_mac):
    subprocess.call(["ifconfig", interface, "hw", "ether", new_mac])

change.mac(options.interface, options.new_mac)

As far as I know, the variables options & arguments are storing the values of whatever parser.parse_args() returns. Now, whenever I call this program in my terminal, it's giving me an error. It's saying that the name options is not defined. How is this possible?

PS: I know the solution is to work with return parser.parse_args(), but I'm just trying to understand why the (options, arguments) = parser.parse_args() doesn't work.

Thanks in advance!

  • 1
    Uh, you never even called the `get_arguments` function. – Aran-Fey Sep 07 '19 at 16:04
  • 1
    and presumably your `import optarse` is actually `import optparse` and your `change.mac` is `change_mac`? Please make sure you copy your *actual* code as what you've posted will throw different errors than you've mentioned :) – Jon Clements Sep 07 '19 at 16:10

1 Answers1

0
  1. The name options is not defined in the global scope you are using it in, since...

  2. You never call the function get_arguments, but...

  3. Even if you did call it, the function get_arguments defines three names parser, options and arguments, by assigning values to them, then implicitly returns None by not returning anything. When Python exits the functions scope, those names are discarded, along with its values, which are not referenced anymore. If you need those values, return them, or assign them to a global variable, which is bad practice, though.

Jan Christoph Terasa
  • 5,781
  • 24
  • 34