Custom standard input for python subprocess

馋奶兔 提交于 2019-12-14 03:42:23

问题


I'm running an SSH process like this:

sshproc = subprocess.Popen([command], shell=True)
exit = os.waitpid(sshproc.pid, 0)[1]

This works and opens an interactive terminal. Based on the documentation for subprocess, sshproc is using the script's sys.stdin.

The question is: how can I print to stderr or a file what input is being received to this child process? I am creating a logging API, and currently lose the ability to record what commands are run over this SSH session.

I don't need the answer, just a nudge in the right direction.

Thanks everyone!

EDIT: It is important that I start the process as shown above so that I can have a interactive SSH session with my user. E.g. I cannot use communicate() as far as I know.


回答1:


sshproc = subprocess.Popen([command],
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        )

stdout_value, stderr_value = sshproc.communicate('through stdin to stdout')
print repr(stdout_value)
print repr(stderr_value)

Ah since you said nudge in right direction, I thought I should point you to good readups:

  • http://www.doughellmann.com/PyMOTW/subprocess/
  • capture stderr from python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

-



来源:https://stackoverflow.com/questions/3729366/custom-standard-input-for-python-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!