【问题标题】:Python script which takes arguments entered in a shell cames with an error接受在 shell 中输入的参数的 Python 脚本出现错误
【发布时间】:2020-04-19 11:02:32
【问题描述】:

我正在开发一个脚本来自动创建 mysql 数据库和数据库的用户创建。它接受在 shell 中输入的参数 -o -dp -dr 使用以下参数(-o 和 -dp)创建 sql 脚本并使用 root 密码(-dr)执行该脚本

from sys import argv
from os import makedirs,system
etc = '/mnt/storage/'
def show_usage():
    print("""
        Create new DB and DB user
        -o object_name
        -dp db user password
        -dr mysql root user password
        """)
    exit(1)

def create_template(object_name, password):
    out = """
            %s template %s example %s %s %s %s
           """%(object_name,object_name,password,object_name,object_name)
    return out

def write_to_sql(object_name, db_password):
    sql_script = open(etc+'new_db_and_user.sql','w+')
    script_to_write = create_template(object_name,db_password)
    sql_script.write(script_to_write)

def execute_sql_script(root_password):
    run_sql_script = "mysql --username=root --password=%s < new_db_and_user.sql"%(root_password)
    remove_sql_script = "rm -f new_db_and_user.sql"
    system(run_sql_script)
    system(remove_sql_script)

try:
    opts, args = getopt.getopt(argv[1:], "hd:s:", ["object_name=","db_password=", "root_password="])
except getopt.GetoptError as err:
    print(str(err))

if opts.__len__() == 0:
    show_usage()

object_name=None
password=None
root_password=None

for option, value in opts:
    if option in ('-o', '--object_name'):
        object_name = value
    elif option in ('-dp', '--db_password'):
        password = value
    elif option in ('-dr', '--root_password'):
        root_password = value
    else:
        print("Unknown parameter used")
        show_usage()


write_to_sql(object_name,password)
execute_sql_script(root_password)

问题

当我使用以下命令执行此脚本时

python create_db.py -o test -dp papa -dr nana

我收到一条错误消息:

option -o not recognized
Traceback (most recent call last):
  File "create_db.py", line 43, in <module>
    if opts.__len__() == 0:
NameError: name 'opts' is not defined

你能帮帮我吗?

【问题讨论】:

    标签: python python-3.x automation getopt


    【解决方案1】:

    当你在输出中得到这个时,

    option -o not recognized

    表示这一行

    opts, args = getopt.getopt(argv[1:], "hd:s:", ["object_name=","db_password=", "root_password="])

    失败了。所以执行落入异常处理程序

    except getopt.GetoptError as err:
        print(str(err))
    

    因此根本没有创建变量opts

    您可以通过首先在opts, args = ... 行之前定义变量来轻松修复它。例如

    try:
        opts = []  # Define the variable opts
        opts, args = getopt.getopt(argv[1:], "hd:s:", ["object_name=","db_password=", "root_password="])
    except getopt.GetoptError as err:
        print(str(err))
    

    【讨论】:

    • 尝试了你的解决方案,但它仍然给出一个错误,说 -o 无法识别try: opts = [] opts, args = getopt.getopt(argv[1:], "hd:s:", ["object_name=","db_password=","root_password="]) except getopt.GetoptError as err: print(str(err))
    • 但如果我像python create_db.py --object_name=test --db_password=papa --root_password=nana这样长时间传递参数,它似乎可以工作
    • 因为"hd:s:"中没有o:
    猜你喜欢
    • 1970-01-01
    • 2014-05-28
    • 2022-01-13
    • 2016-04-04
    • 1970-01-01
    • 2015-09-15
    • 2015-11-26
    • 2022-10-23
    • 2021-06-07
    相关资源
    最近更新 更多