【发布时间】:2012-07-21 05:22:18
【问题描述】:
我必须从命令行输入参数,即用户名、密码和数据库名称。我知道如何在不使用标志的情况下使用sys.argv 来做到这一点,如下所示:
##Test.py
hostname = str(sys.argv[1])
username = str(sys.argv[2])
password = str(sys.argv[3])
def ConnecttoDB():
try:
con=sql.connect(host=hostname, user= username, passwd= password)
print ('\nConnected to Database\n')
# If we cannot connect to the database, send an error to the user and exit the program.
except sql.Error:
print ("Error %d: %s" % (sql.Error.args[0],sql.Error.args[1]))
sys.exit(1)
return con
所以,它可以这样运行:
$test.py DATABASE USERNAME PASWORD
但问题是我必须使用“标志”。所以,脚本可以这样运行:
$test.py -db DATABSE -u USERNAME -p PASSWORD -size 20
如何使用标志从命令行获取参数?
【问题讨论】:
标签: python command-line python-3.x arguments