pymssql 连接函数

0 投票
2 回答
905 浏览
提问于 2025-04-15 20:13

我有一个函数:

pymssql.connect(host="我的主机", user="我的用户名", password="我的密码", database="我的数据库")

我想从用户那里读取用户名和密码,然后把它们放到这个函数里,这样可以吗?或者说,像这种命名参数的值不能是变量吗?如果可以的话,我该怎么做呢?

比如说,能不能像这样调用这个函数:

pymssql.connect(host=变量,...)

2 个回答

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

然后你可以像这样使用命名参数:

myfun(named=myvar, named2=myvar2)
3

你的问题表述得有点奇怪。你是在问如何在函数定义中设置默认参数吗?

>>> 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

在Python中,使用None作为缺失参数的标志值是一种常见的做法,这样可以检测到缺失的参数并执行其他函数。

撰写回答