Python 将getpass与psycog一起用于密码管理时出现问题

Python 将getpass与psycog一起用于密码管理时出现问题,python,python-3.5,psycopg2,postgresql-9.3,getpass,Python,Python 3.5,Psycopg2,Postgresql 9.3,Getpass,我的目标是,当我通过python3连接到postgresql数据库时,使用getpass隐藏密码条目。 我在jyputer笔记本上使用python3 这项工作很好: connect = psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password='123456'") cur = connect.cursor() 但当我尝试使用单独的变量输入密码时,它不再起作用: pw = getpa

我的目标是,当我通过python3连接到postgresql数据库时,使用getpass隐藏密码条目。 我在jyputer笔记本上使用python3

这项工作很好:

connect = psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password='123456'")
cur = connect.cursor()
但当我尝试使用单独的变量输入密码时,它不再起作用:

pw = getpass.getpass() 
####Python ask me to tape password and i tape the same '123456'
要验证:

'123456'

connect=psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password=pw")
cur=connect.cursor()


感谢您的帮助

您正在做的是向
连接
函数传递字符串。此字符串的值为
“dbname='db\u toto'user='dad'host='xx.xx.xxx.x'port='5432'password=pw”
psycopg2
模块无法知道什么是
pw
。我怀疑它会被转换成字符串(
'pw'
),但我不确定

无论如何,正确的方法是将关键字参数传递给
connect
函数,如下所示:

connect = psycopg2.connect(dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password=pw)
# Notice the lack of double-quotes in the arguments
这样,您将把
pw
变量的内容传递给函数,而不是名称
pw

也可以以字符串形式传递
pw
变量的内容,如下所示:

connect = psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password='{}'".format(pw))

第一个表单应该是首选的。

您传递的密码是
pw
,而不是
123456
,正如我预期的那样。第二个表单(xxx.format(pw))运行良好。第一个服务器再次发送相同的错误。所以我用第二个。多谢各位
connect = psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password='{}'".format(pw))