Accessing Variable of exe file in Python

I have an .exe file generated by Visual Studio which reads the data from the serial device and prints the output of the device on the window.
I want to read that value in my Python variable continuously while exe is running in the background.
I tried it with “subprocess” module of the python But what it is doing is that it is printing whole screen at once. What I want is to read the particular variable of Visual Studio code in some python variable.
Any Help would be appreciated.

What did you try, exactly?

What do you mean by “printing the whole screen”? Please explain what result you would like to have, and show an example of what you are seeing instead.

How are you using subprocess to call your exe file? Typically, you would do something like

result = subprocess.run(["<your_exe>"], capture_output=True)
output = result.stdout

The output variable will now contain whatever your exe spat out.

If what you are really trying to achieve is reading data from a serial port, rather than interfacing with this specific exe file, you may want to look into using pyserial instead.

1 Like

In my C# program in Visual Studio, there are multiple variables that I am trying to print on the windows console let’s say 10 variables, what I want is to read only one particular variable in python and store it in the list.
As My exe is reading serial data correctly so I don’t need pyserial.
“Printing the whole screen” means whatever output of exe is printing on the window console same is printing on python output console, I have used subprocess.run([“<your_exe>”], capture_output=True)

Suppose below is my program(This is just for an Example):
int main()
{
int a = 0;
int b = 0;
while(True)
{ printf(“%d %d”,a,b);
a++;
b++; delay(1000);
}
}
Now I will compile, and I will have .exe file
Now I will run this exe in the background and want to read the value of variable “a” only in my python script, not “b” ,But What I am getting on my python console is:
0 0
1 1
2 2
3 3

Python has no way of knowing what variables exist in your C# program or what they are called. In your example, you want to stream the output from your program and discard the second column. This can be done using Popen:

from subprocess import Popen, PIPE

with Popen(["<your_exe>"], stdout=PIPE, text=True) as proc:
    while line := proc.stdout.readline():
        a = line.split()[0]
        # Do something with a.

Adapt as needed based on what your actual program outputs.

1 Like

Thanks Alexander Bessman, The code is working now.