0

I have the code where stdout works for popen command, now how do I modify so I can send something to its 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

output["result"], output["error"] = ch.communicate(input=stdin_in)[0] #STUCK print output["result"] # works

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

if __name__ == '__main__':
    main()

so I can send the password string to myprogram ?

------modified -----------

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: ') 

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

prints

('', 'Password: ')

Victor
  • 427
  • 1
  • 6
  • 19
  • Possible duplicate http://stackoverflow.com/questions/163542/python-how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument#165662 – Alex Feb 27 '17 at 20:29
  • changing the line to : output["result"], output["error"] = ch.communicate(input=stdin_in)[0] #got stuck – Victor Feb 27 '17 at 20:57

0 Answers0