How to interact with a Terminal in python

假装没事ソ 提交于 2019-12-13 04:51:22

问题


I'm working on a small script. The script should open 3 terminals and interact with this terminals independently.

I am pretty understand that subprocess is the best way to do that. What I've done so far:

# /usr/bin/env python
import subprocess

term1 = subprocess.Popen(["open", "-a", "Terminal"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
term1.communicate(input="pwd")

My problem is I cannot interact with a new terminal. this part term1.communicate(input="pwd") is not working. I cannot send a command to a new Terminal. I also tried term1.communicate(input="pwd\n") but nothing happens

Do you any ideas how can I do that?

P.S. I am using Mac OS.


回答1:


You can run both commands concurrently without opening terminals.

import subprocess
process1 = subprocess.Popen(["ls", "-l"])
process2 = subprocess.Popen(["ls", "-l"])

If you run that code you will see that the directory is listed twice, interleaved together. You can expand this for your specific needs:

tcprelay1 = subprocess.Popen(["tcprelay", "telnet"])
tcprelay2 = subprocess.Popen(["tcprelay", "--portoffset [arg1] [arg2]")


来源:https://stackoverflow.com/questions/25815078/how-to-interact-with-a-terminal-in-python

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