How to interact with a Terminal in python

2019-08-19 06:16发布

问题:

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