开发者

Bug import main with arguments in Python

In a script I'm trying to import the main module from another script with an argument.

I get the error message "NameError: global name 'model' is not defined".

If someone sees the mistake, I'd be grateful !

My code :

script1

#!/usr/bin/python

import sys
import getopt
import pdb
import shelve

class Car:
    """ class representing a car object """
    def __init__(self, model):
        self.model = model

class Porsche(Car):
    """ class representing a Porsche """
    def __init__(self, model):       
        Car.__init__(self, model)
        print "I have a Porsche but no driving licence : too bad !"

# Main
def main(argv):

    settings = shelve.open('mySettings')
    global model
    try:
        opts, args = getopt.getopt(argv, "m:", ["model="])
    except getopt.GetoptError, err:
           print " wrong argument, exiting "
           sys.exit()
    for opt, arg in opts:
        if opt in ("-m", "--model"):
            model = arg

    def choose_car(model):
        """ Creates the car"""
        my_Porsche = Por开发者_JAVA百科sche(model)     

    choose_car(model)

if __name__ == "__main__":
   main(sys.argv[1:]) 

script2

#!/usr/bin/python

import os
import sample
import sys

def main(argv):
        script1.main("-m Carrera")

# Main program
if __name__ == '__main__':
    main(sys.argv[1:])

rgds,


argv is a list. Therefore you should call script1.main as

script1.main(['-m', 'Carrera'])

or, equivalently,

script1.main('-m Carrera'.split())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜