7

当用户在控制台中运行脚本时,我需要隐藏密码(如下所示:)mysql -p。对于我使用的输入参数argparse,如何添加getpass密码参数?

parser = argparse.ArgumentParser()
parser.add_argument('-p', action='store', dest='password', type=getpass.getpass())

当我运行我的脚本时:python script.py -u User -p 我得到单独的输入密码行(Password:),但在输入 Exception: 后ValueError: 'my_password' is not callable引发。

4

4 回答 4

8

这个人应该可以解决你的问题:getpass

这是一个带有自定义操作的示例

class PwdAction(argparse.Action):

     def __call__(self, parser, namespace, values, option_string=None):
         mypass = getpass.getpass()
         setattr(namespace, self.dest, mypass)

parser = argparse.ArgumentParser()
parser.add_argument('-f', action=PwdAction, nargs=0)
于 2015-04-29T15:49:02.627 回答
7

EDIT: My previous answer was incorrect and based on a guess. This was my attempt at a working solution. @qwattash posted the answer correctly first but since I spent ten minutes working it out I thought I'd correct my answer.

import argparse
import getpass

class Password(argparse.Action):
    def __call__(self, parser, namespace, values, option_string):
        if values is None:
            values = getpass.getpass()
        setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument('-p', action=Password, nargs='?', dest='password')
args = parser.parse_args()

password = args.password #either from command line or from prompt
于 2015-04-29T15:52:03.270 回答
0

您应该重命名进程名称。也许你正在寻找这个:

pip install setproctitle

https://github.com/dvarrazzo/py-setproctitle

于 2021-04-11T09:03:43.683 回答
-1

简短的回答:不,你不能!

argparse模块不打算这样做。您应该在其他单独的过程中询问密码。此外,type参数只是在存储值之前使用的值转换器。

于 2015-04-29T15:57:01.037 回答