0

I have created an application using Tkinter , it will connect to SSH and run few commands. This process is running in a loop using scheduler. After 1st iteration , command prompt gets stuck and wont resume its display till I press enter. It just wont display output on command prompt. I am writing that output into a file. even file is not getting updated till I press any key at command prompt. Looks like it waits for some input/key stroke to start next iteration. After pressing enter I can see that it was already running at background as suddenly it displays lots of output on the screen. How to run/display/focus it continuously ? I am using a scheduler so that my job will keep on running for few hours. But due to command prompt stuck issue I can not see whether my program is running or not using command prompt.

If I keep open my command prompt window , everything works smoothly, output window appears and output gets written into the file, if the window is minimized , output window does not show up and file is not getting updated. Looks like it only works when it is in focus ( command prompt is not minimized) Please help.

code is here:

import tkinter.messagebox
import paramiko
import time
from datetime import datetime, timedelta
import tkinter.messagebox
import tkinter
import sys
import apscheduler
from apscheduler.schedulers.blocking import BlockingScheduler
import babel.numbers # for exe


def display_output(targetopname):

    hostname_ip = "192.168.1.101"
    username = "admin"
    password = "admin"

    # create /append output file
    output_file = open(targetopname, "a+")
    port = 22

    i = 0
    while True:
        try:
            ssh = paramiko.SSHClient()
            #ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname_ip, 22, username, password)
            break
        except paramiko.AuthenticationException:
            print("Authentication failed when connecting to %s" % hostname_ip)
            sys.exit(1)
        except:
            print("Could not SSH to %s, waiting for it to start" % hostname_ip)
            i += 1
            time.sleep(2)
            if i == 3:
                print("Could not connect to %s. Giving up" % hostname_ip)
                sys.exit(1)

    cmd_list = list()
    c1 = "config global"
    c2 = "get sys status"
    c3 = "end"

    cmd_list.append(c1)
    cmd_list.append(c2)
    cmd_list.append(c3)

    op_tk = tkinter.Tk()
    op_tk.wm_title("p2trial")
    op_tk.geometry("600x400")

    op_text_window = tkinter.Text(op_tk, height=600, width=400)
    op_scrollbar = tkinter.Scrollbar(op_tk)
    op_scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    op_scrollbar.config(command=op_text_window.yview)
    op_text_window.pack(side=tkinter.LEFT, fill=tkinter.Y)

    channel = ssh.invoke_shell()
    for command in cmd_list:
        time.sleep(1)
        channel.send(command + '\n')
        time.sleep(0.30)
        if channel.recv_ready():
            time.sleep(0.30)
            outlines = channel.recv(10240).decode("ascii")
            op_text_window.insert(tkinter.END, outlines)
            op_text_window.pack(side=tkinter.LEFT, fill=tkinter.Y)
            op_tk.update()
            output_file.write(outlines)
        else:
            print("\nNo data for command ", command)

    time.sleep(2)
    channel.close()
    ssh.close()
    output_file.close()
    op_tk.destroy()
    dtnow = datetime.now()
    print("\n*** End of the function  ", dtnow)


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    x = datetime.now() + timedelta(seconds=1)
    x += timedelta(seconds=1)
    targetfilename = "output.txt"

    scheduler.add_job(display_output, 'interval',  minutes=3,
                      max_instances=5, start_date=x,
                      end_date='2021-10-12 11:00:00.000000',args=[targetfilename])
    scheduler.start()
user_PM
  • 45
  • 7
  • How to keep program/display running even if I am working on another task, and command prompt is not in focus – user_PM Oct 08 '21 at 10:01
  • please provide [mre] and remove the comment and [edit] that info in the question – Matiiss Oct 08 '21 at 10:22
  • let me right one as the entire program is huge. – user_PM Oct 08 '21 at 11:34
  • Added the code here. – user_PM Oct 12 '21 at 12:02
  • that is not a [mre], also if you have `input()` in your code, that part should be put in another thread or any other GUI blocking code should be put into a separate thread – Matiiss Oct 12 '21 at 12:07
  • I skipped the input part as it will be a huge code. and its not affecting the nature of the problem. I don't know , exactly which part of the code is blocking GUI. – user_PM Oct 12 '21 at 14:21
  • Ok, in the given code all of the `while` and `for` loops are what is blocking the GUI – Matiiss Oct 12 '21 at 16:47
  • 1
    Does this answer your question? [How do you run your own code alongside Tkinter's event loop?](https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop) – Matiiss Oct 12 '21 at 16:49
  • Thank you Matiiss , I have gone through that post, let me try few things. Instead of 'after' I like scheduler more, as I have to run job after every X minutes, irrespective of whatever time took by job to execute. I have skipped mainloop() as I am updating text for every output. – user_PM Oct 14 '21 at 05:29
  • Ok, btw, what happens if a job is still running but another one has to start? Is the running job terminated or is the new job started on yet another new thread? Also do you need the user to be able to choose the time between jobs? Also does each job have to be written on its own text widget? Anyways besides all that, you can run the whole scheduler in another thread (or maybe tkinter) and then you can easily have the mainloop, will try to figure sth out unless you don't need any help with this specific question anymore. – Matiiss Oct 14 '21 at 05:44
  • scheduler has property max_instances, which will help us to run jobs in parallel – user_PM Oct 18 '21 at 07:18

1 Answers1

0

Looks like it is related to command prompt and not tkinter. I have referred the solution : Command prompt gets stuck and continues on enter key press

It is solving my problem. Thank you everyone.

user_PM
  • 45
  • 7