0

在一个脚本中,我试图从另一个带有参数的脚本中导入主模块。

我收到错误消息“NameError:未定义全局名称‘模型’”。

如果有人看到错误,我将不胜感激!

我的代码:

脚本1

#!/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 = Porsche(model)     

    choose_car(model)

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

脚本2

#!/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,

4

1 回答 1

3

argv是一个列表。script1.main因此,您应该调用

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

或者,等效地,

script1.main('-m Carrera'.split())
于 2010-08-24T13:31:48.350 回答