我有这个功能 pymssql.connect(host =“my host”,user =“my user”,password =“my pass”,database =“mydb”)
我想从用户那里读取用户和密码并将它们放在那里可能或命名参数lvalue不应该是变量的,如果是,那我怎么能这样做?
即可以调用此函数,如: pymssql,连接(主机= varaible,...)
答案 0 :(得分:3)
你的问题措辞奇怪......你在函数定义中遇到setting default arguments有问题吗?
>>> def f(arg1="hello", arg2="goodbye"):
print "arg1 is", arg1
print "arg2 is", arg2
>>> f()
arg1 is hello
arg2 is goodbye
>>> f(arg2="two")
arg1 is hello
arg2 is two
>>> f(1,2)
arg1 is 1
arg2 is 2
>>> f(arg2="foo", arg1="bar")
arg1 is bar
arg2 is foo
如果那不是你想要的,你想提示用户缺少参数吗?
>>> def g(arg=None):
if arg is None:
arg = raw_input("What is the argument?")
print "The argument was", arg
>>> g(123)
The argument was 123
>>> g()
What is the argument? foo bar
The argument was foo bar
对于缺少的参数使用None的sentinel值是Python中用于检测缺少的参数并执行另一个函数的惯用方法。
答案 1 :(得分:0)
要从用户读取输入,您可以使用raw_input
要使用该程序的命令行参数,您必须import sys
并使用sys.argv
例如:
import sys
myvar = raw_input("please input a var") #prompts the user for a value
myvar2 = sys.argv[1] #gets the first argument to the program
然后你可以使用像
这样的命名argsmyfun(named=myvar, named2=myvar2)