i have this function pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")
I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?
i.e is it possible to call this function like: pymssql,connect(host=varaible,...)
-
2Mark is right: you seem to have a poor grasp of how Python functions deal with optional arguments. There are a number of good books out there plus tons of good, free tutorials for people just getting started with the language. For Example Python for Software Design: How to Think Like a Computer Scientist has a free, downloadable copy @ greenteapress.com/thinkpython .Peter Rowell– Peter Rowell2010年03月09日 17:53:53 +00:00Commented Mar 9, 2010 at 17:53
-
What i mean if i can call a function like that : f(arg1=var) where var is variableoren– oren2010年03月09日 18:00:36 +00:00Commented Mar 9, 2010 at 18:00
2 Answers 2
Your question is worded... strangely. Are you having trouble with setting default arguments in a function definition?
>>> 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
If that wasn't what you were looking for, did you want to prompt the user for a missing argument?
>>> 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
Using a sentinel value of None for a missing argument is the idiomatic way in Python to detect a missing argument and execute another function.
Comments
To read input in from the user you can use raw_input.
To use the command line arguments of the program you have to import sys and use sys.argv
for example:
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
you can then use the named args like
myfun(named=myvar, named2=myvar2)