Friday, 4 September 2020

How can I use Python to interact with a command line multiple times without losing instance specific variables like working directory?

I am trying to simulate a command prompt inside of my program (like the one at the bottom of VS Code, for example).

Here is what I have tried:

import os

while(True):
    console_command = input()
    console_stream = os.popen(console_command)
    console_output = console_stream.read()
    print(console_output)

This almost works, but current directory and other runtime specific data is lost because os.popen opens a new instance of the terminal every time it calls a command. Most importantly, it is impossible to use the cd command to change directories when using this implementation.

I have also considered storing each time the user calls a command that changes directory and appending these calls to the front of any commands the user runs, but this seems like a bad idea because it can cause errors if the user modifies the directory. It would also make my code very messy and it would take a lot of memory.

Note - this is not a duplicate of other questions asking how to run a command in python because I need to run multiple commands in the same terminal and offer live responses. Combining multiple commands into a single line is not an option.



from How can I use Python to interact with a command line multiple times without losing instance specific variables like working directory?

No comments:

Post a Comment