1

I am attempting to create a basic terminal emulator.

Currently my code takes input, and pastes it straight into Subprocess.run.

import subprocess
while True:
    command = input("Input:")
    result = subprocess.run(
              command.split(),
              capture_output=True,
              encoding="utf-8")
    
    result.check_returncode()
    result = result.stdout
    print(result)

I would like to be able to run a series of commands in the same prompt.

For example, I would like to input

cd /Desktop
ls

and then

cat myfile.txt

However, "cd" returns an error:

> [Errno 2] No such file or directory: 'cd'

Presumably, this is because subprocess.run creates a new subprocess for each command, so there is no point in such a command being supported.

Similarly, the problem rearises when inputting a command that requires sudo, eg

> sudo mount /dev/sda1 /home/sda1

I am therefore wondering how subprocess (or a different library) can be used to run a series of processes in the same terminal in series, simply pasting plain text into a terminal and recieving the output back as plain text, with the ability to send commands to the same subprocess, rather then a new spawned subprocess.

(I am aware that such a utility creates a severe security issue, as it gives a program full access to the terminal)

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Yimeca
  • 21
  • 3
  • 1
    You are trying to write a shell not Terminal Emulator, right? Shell takes these commands as input; TE is something that takes care of the basic editing, sending data to shell, displaying etc. Also, `cd` changes the current director of the program, it is not an executable like others. – Nishant Jun 26 '22 at 20:11
  • 3
    `cd` is not an executable, it's a built-in command of the shell – Thomas Weller Jun 26 '22 at 20:12
  • 1
    Before you get any ideas, using `shell=True` will make the command "work". Except the newly changed directory will expire with the process it ran in (the subprocess shell), and it's therefore thoroughly useless. Use `os.chdir`. – ShadowRanger Jun 26 '22 at 20:22

0 Answers0