简体   繁体   English

如何在不使用子流程或pexpect模块的情况下将输入值发送到终端

[英]How to send input values to terminal without using subprocess or pexpect modules

I am trying to write unit tests for a python script. 我正在尝试为python脚本编写单元测试。 My script takes user input whether proxy credentials are required or not. 无论是否需要代理凭据,我的脚本都会接受用户输入。 I have seen several answer-1 , answer-2 , answer-3 like executing with subprocess and pexpect. 我已经看到了几个answer-1answer-2answer-3,就像用subprocess和pexpect执行一样。 But my intention is that after taking user input, I have to execute other functions in the script. 但是我的意图是,在接受用户输入后,我必须在脚本中执行其他功能。 So executing the script doesn't help. 因此,执行脚本无济于事。 My python script is below. 我的python脚本如下。 Can someone provide me suggestions or with a way to achieve this? 有人可以向我提供建议或实现该建议的方法吗?

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

I want to send input value when Enter credentials : Y/N is prompted. 我想在提示Enter credentials : Y/N时发送输入值Enter credentials : Y/N否。

Actually, this is a duplicate question.I am not deleting this as it might be useful for someone else. 实际上,这是一个重复的问题,我没有删除它,因为它可能对其他人有用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM