【问题标题】:How to send input values to terminal without using subprocess or pexpect modules如何在不使用 subprocess 或 pexpect 模块的情况下将输入值发送到终端
【发布时间】:2019-04-15 11:19:34
【问题描述】:

我正在尝试为 python 脚本编写单元测试。无论是否需要代理凭据,我的脚本都会接受用户输入。我见过几个answer-1answer-2answer-3,比如用 subprocess 和 pexpect 执行。但我的意图是在接受用户输入后,我必须执行脚本中的其他功能。所以执行脚本没有帮助。我的python脚本如下。有人可以为我提供建议或实现此目标的方法吗?

import getpass
class ProxyDetails:
    def __init__(self,option):
        self.option = option
        self.proxy_option = self.get_web_proxy_details()
        self.call_request()
        self.parse_test()

    def get_web_proxy_details(self):
        if self.option == "Default":
            choice = raw_input("Enter credentials : Y/N ").lower()
            if choice.lower() == "y":
                self.proxy_username = getpass.getpass("Enter Username for Proxy : ")
                self.proxy_password = getpass.getpass("Enter Password for Proxy : ")
                self.requireProxyCredentials = "Y"
            elif choice.lower() == "n":
                print("credentials are not present ")
        else:
            print("proxy is none ")

    def call_request(self):
        # this method will do API call
        pass
    def parse_test(self):
        #this method will parse the json
        pass

obj=ProxyDetails(option="Default")

我想在提示Enter credentials : Y/N 时发送输入值。

【问题讨论】:

    标签: python


    【解决方案1】:

    实际上,这是一个duplicate 问题。我不会删除它,因为它可能对其他人有用。

    import sys
    import StringIO
    f1 = sys.stdin
    f = StringIO.StringIO('n') 
    sys.stdin = f
    obj=ProxyDetails(option="Default")
    sys.stdin = f1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多