Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to not break the input of a command while a thread is writing data in the terminal in python3?

$
0
0

i was developing a client/server cli application and i encoutered a problem with the input() function of python3 and multi-threading.

Here is a code for the example:

import threadingimport timedef thread_function():    for i in range(10):        time.sleep(3)        print(f"[Thread {i}]")while True:    thread = threading.Thread(target=thread_function)    thread.start()    command = input("input> ")    print("Command:",super1)

This code prompt a command and outputs it, while a thread is running and displaying data on a screen at random time (every 3 seconds in this case). When i'm entering the value in the prompt, if the thread displays an information, my entry will be splited in half as following (example for a whoami):

input> who[Thread 0]amiCommand:whoami

I'm looking for a way to get something like that:

intput> who[Thread 0]intput> whoami

In this example, i would type the beginning of the command before the thread output, and then complete it after the thread output. It must also support the "remove" key.

The thread data must be fully interactive, when the thread needs to display the information, it has to be displayed at the same time in the cli console (cannot wait the end of the input function).

I already tried to use sys.stdin and readchar, but i didnt find a good way to implement this.

If someone has an idea to implement this kind of thing, i would be really happy to discuss about it :)

Thanks

Tried to use sys.stdin and readchar, but i didnt find a good way to implement this.

With readchar, it was a bit complicated to follow the char list and to display the good thing (thread side), and it didnt handle the del key.

With sys.stdin it was impossible to get the full command char by char.

EDIT:

For this project, i really need to get the output of the thread at the same time of the main thread running (this thread will be 50% of the time locked by an input). If the thread output the value after a carriage return, i would miss some data :/ . I can give you the context (better than an example). The project i am currently working on is : https://github.com/Ph3nX-Z/LightC2 ,the problem i exposed in my post is located in the libs.client.cliclient script, in the interact_with_agent func in the while True statement. In this function, i would need to get the output of the command at any time, and at the same time be able to type a command without beeing interrupted by an output from an agent :)

Maybe if i can split the terminal or check if an user is typing smth in the input statement it would help


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>