Python 2.7.11 getopt 不读取参数

Python 2.7.11 getopt doesn't read the argument

在 Python 2.7.13

我们有以下 python 代码来获取命令行参数:

import sys
import csv
import os
import sys, getopt
import pandas as pd
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)


def main():

    SERVER_NAME=''

    PORT_NAME=''

    PASSWORD=''

    try:

        opts, args = getopt.getopt(sys.argv[1:],"hs:p:x:",["server=","port=","password="])

    except getopt.GetoptError:

        print 'help'

        sys.exit(2)

    for o, a in opts:

        if o == '-h':

            print '\n'+'-s / --server (required)'  

            print '\n'+'-p or --port (required)'

            print '\n'+'-x or --password (required)'

            sys.exit()

        elif o in ("-s", "--server"):

            SERVER_NAME = a

        elif o in ("-p", "--port"):

            PORT_NAME = a

        elif o in ("-x", "--password"):

            PASSWORD = a

        else:

            assert False, "No command line option.  To see the options, plese use -h"


if __name__ == "__main__":

    main()

print SERVER_NAME

dbServer=SERVER_NAME

但是,当运行命令行中出现以上代码时:

python test.py -s AAA -p BBB -x CCC

将出现以下错误:

print SERVER_NAME
NameError: name 'SERVER_NAME' is not defined

有哪位大神能指教一下这里有什么问题吗?谢谢

SERVER_NAME 被定义为 main() 函数的局部变量,因为它在全局范围内不可见(代码底部的行。
您可以将 SERVER_NAME 设为全局变量,或者将调用 main() 之后的代码移动到 main() 中。我更喜欢后者;当我用这样的 CLI 编写代码时,在调用 main() 之后我没有任何代码(我通常在该调用之前有全局设置代码,但是 none 取决于 main函数)

我的意思是 'moving code into main':

dbServer = ''

def main():
    global dbServer
    SERVER_NAME=''
    PORT_NAME=''
    PASSWORD=''
    try:
        opts, args = getopt.getopt(sys.argv[1:],"hs:p:x:", ["server=","port=","password="])
    except getopt.GetoptError:
        print 'help'
        sys.exit(2)

    for o, a in opts:
        if o == '-h':
            print '\n'+'-s / --server (required)'  
            print '\n'+'-p or --port (required)'
            print '\n'+'-x or --password (required)'
            sys.exit()
        elif o in ("-s", "--server"):
            SERVER_NAME = a
        elif o in ("-p", "--port"):
            PORT_NAME = a
        elif o in ("-x", "--password"):
            PASSWORD = a
        else:
            assert False, "No command line option.  To see the options, plese use -h"

    print SERVER_NAME
    dbServer=SERVER_NAME    

if __name__ == "__main__":
    main()