How do i open a new terminal in python and control it?

166 views Asked by At

how do I, crossplatform, open a new terminal window and control it? I want to be able to send text to the terminal, and recieve keyboard inputs, without needing to run in console mode, as this program will be running as a pyw and not py.

I havent tried anything yet, as i still am thinking about how i want to go about this.

2

There are 2 answers

1
Saxtheowl On

The subprocess module can help you there. Something like that:

import subprocess
import sys

def open_terminal():
    if sys.platform == 'win32':
        subprocess.Popen('start', shell=True)
    elif sys.platform == 'darwin':
        subprocess.Popen('open -a Terminal .', shell=True)
    else:
        try:
            subprocess.Popen('gnome-terminal', shell=True)
        except FileNotFoundError:
            try:
                subprocess.Popen('xterm', shell=True)
            except FileNotFoundError:
                print("Unsupported platform")
                sys.exit(1)

open_terminal()
3
Rémi.T On

You can maybe use os module. With it, you can easily execute terminal commands. To get keyboard input there is various module you can use, like keyboard module:

import keyboard

while True:  # Loop to capture keys continuously
    event = keyboard.read_event()  # Capture a keyboard event

    if event.name == 'q' and event.event_type == 'down':
        print("Q key was pressed.")
        break
    elif event.event_type == 'down':
        print(f"{event.name} key was pressed")