How to collect continuous data with Python Telnet
<p>I have a python script that connects to a Power Supply via a Telnet session. The flow of the script is as follows:</p>

<pre><code># Connect to Device
tn = telnetlib.Telnet(HOST,PORT)

# Turn On
tn.write("OUT 1\r")

# Get Current Voltage
current_voltage = tn.write("MV?\r")

# Turn Off
tn.write("OUT 0\r")
</code></pre>

<p>What I'd like to do is be able to get the Current Voltage every t milliseconds(ms) and be able to display it on my Tkinter GUI until the device is commanded to be turned off. Ideally I'd like to display it on a chart such that I have Voltage vs. time, but i can live with just a dynamic text display for now. The <code>current_voltage</code> variable will store a string representing the current voltage value. What is the best way I can accomplish this? Thanks.</p>

<p>Every millisecond is probably more than tkinter can handle. It depends a bit on how expensive it is to fetch the voltage. If it takes longer than a millisecond, you're going to need threads or multiprocessing. </p>

<p>The simplest solution is to use <code>after</code> to schedule the retrieval of the data every millisecond, though again, I'm not sure it can keep up. The problem is that the event loop needs time to process events, and giving it such a tiny window of time when it's not fetching voltages may result in a laggy GUI.</p>

<p>The general technique is to write a function that does some work, and then calls <code>after</code> to have itself called again in the future. </p>

<p>For example:</p>

<pre><code>root = tk.Tk()
...
def get_voltage():
    &lt;your code to get the voltage goes here&gt;

    # get the voltage again in one millisecond
    root.after(1, get_voltage)
...
get_voltage()
root.mainloop()
</code></pre>

<p>the other choice is to use threads, where you have a thread that does nothing but get the voltage information and put it on a queue. Then, using the same technique as above, you can pull the latest voltage(s) off of the queue for display.</p>

python tkinter telnet