如何将字符串传递给subprocess.Popen

时间:2017-02-27 20:20:43

标签: python

我有stdout用于popen命令的代码,现在我如何修改以便可以向stdin发送内容。

def runcmd(command, stdin_in):
    output = {"result": [], "error": [], "exit_status": []}

    ch = subprocess.Popen(command,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True,
                                 close_fds=True)

    output["result"], output["error"] = ch.communicate() #capture it

输出[“结果”],输出[“错误”] = ch.communicate(输入= stdin_in)[0] #STUCK         print output [“result”]#works

def main():
    password_string = "abc123"
    runcmd ("myprogram hostname" , password_string)

if __name__ == '__main__':
    main()

所以我可以将密码字符串发送到myprogram?

------修改-----------

output = {"result": [], "error": [], "exit_status": []}

ch = subprocess.Popen(command,
                      stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             shell=True,
                             close_fds=True)

output= ch.communicate(input=stdin_in)
print output[1]  # Prints ('', 'Password: ') 

-----------修改2 ------------

class Actions():

    def console(self):
        return subprocess.Popen("myprogram",
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True,
                         close_fds=True)


    def password(self, passw):
        delete = self.console().communicate("%s" % (passw))
        return(delete)


def main():
    password_string = "abc123"
    print Actions().password(password_string)

打印

('','密码:')

0 个答案:

没有答案
相关问题