Thanks to the comment of @joan:

You can't. A C program (a program in any language) returns an integer status. You want to change the Python program so it gets the stdout (printf) of the C program rather than the status of the C program.

I do this in Python:

>>> from subprocess import check_output
>>> foo = check_output('./th', shell=True)
>>> foo
'17.9 51.0'
Answer from allcaps on Stack Exchange
🌐
Reddit
reddit.com › r/learnprogramming › how do i create a python file that interacts with c executable, and saves its output to variables?
r/learnprogramming on Reddit: How do I create a python file that interacts with c executable, and saves its output to variables?
February 3, 2022 -

Hi, I have this simple c program:

#include <stdio.h>
void secretFunction() { printf("Congratulations!\n"); printf("You have entered in the secret function!\n"); }
void echo() { char buffer[20];
printf("Enter some text:\n"); scanf("%s", buffer); printf("You entered: %s\n", buffer);}
int main() { echo();
return 0; }

It includes a buffer overflow, but that's not really the important part right now. This is what the output looks like:

Enter some text:
enteringmyname
You entered: enteringmyname

What I am trying to do, is create a python file that is able to run this file, save the lines that it gives to some variables, and then give it some input depending on that output.

Currently this is what I have:

import subprocess

p = subprocess.Popen("./vuln_nostack", shell=False)

p.communicate()

This runs the file like I want, and then just runs the file in the python terminal.

This is not reaaally what I want though.

I want to be able to save the lines that it outputs to variables in my python program, and then output something.

I then tried all kinds of things to make a program that could interact a little more with the executable.

I made a python script that imitates, and does the same thing as the c program:

inp = input("Enter some text:\n")
print("you entered: " + inp)

And then I made this python program to interact with it:

import subprocess
command = "python3 dummy.py"
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
v = p.stdout.readline() print(v) output, err = p.communicate(input="{}\n".format(v))
print(output)

and this does exactly what I want, I can save the ouput, and input something based on it.

But when I run this exact same program, but instead point it to the c executable, the program just hangs, and nothing happens.

Why does this happen? and can I get my python file to talk to the executable in the way that I want?

How the hell do I run a program in C? Jul 5, 2023
r/cprogramming
3y ago
how to run an exe through python? Feb 8, 2026
r/learnpython
7mo ago
How to interop between C and python Jun 4, 2023
r/C_Programming
3y ago
How do I save and run my code? Jan 21, 2021
r/learnpython
5y ago
More results from reddit.com
Discussions

windows - Capture stdout from a running C program with Python - Stack Overflow
What should I get? It runs and it puts output into the console without any surprises. – Anton Kapelyushok Commented Mar 18, 2015 at 22:13 · Maybe I'm misunderstanding your first comment. Since the C program prints to the console without an issue, it's not being buffered. Therefore, I suspect Python ... More on stackoverflow.com
🌐 stackoverflow.com
March 19, 2015
Run C program from Python and then capture output - Stack Overflow
I have a C program that takes two args and outputs a number. ./a.out 2 3 (for example). It does some computational expensive operations, so I was wondering could I use Python's multiprocessing library to run a bunch of the C programs and then compile all the numbers into a list or table or ... More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
Running a C executable inside a python program - Stack Overflow
I have written a C code where I have converted one file format to another file format. To run my C code, I have taken one command line argument : filestem. I executed that code using : ./executable... More on stackoverflow.com
🌐 stackoverflow.com
c++ - Python Script to run a C Program - Stack Overflow
I would like to write a Python script to run this program multiple times for different inputs and write outputs to a file. I am planning to run the program with exhaustive inputs. However, I don't have any experience in writing scripts or programming in Python. So, I was wondering if I could get ... More on stackoverflow.com
🌐 stackoverflow.com
June 5, 2017
🌐
Stack Overflow
stackoverflow.com › questions › 38029813 › obtaining-output-of-a-c-program-in-python
Obtaining output of a C program in python - Stack Overflow
The return value is a special object that contains information about the running process. Popen doesn't wait for the process to return. ... command = ['./serialize', binary, str(width), str(height)] stdout, stderr = subprocess.check_output(command) print stdout, stderr · If you want both stdout and stderr in one string, do:
🌐
Stack Overflow
stackoverflow.com › questions › 29132214 › capture-stdout-from-a-running-c-program-with-python
windows - Capture stdout from a running C program with Python - Stack Overflow
March 19, 2015 - What should I get? It runs and it puts output into the console without any surprises. – Anton Kapelyushok Commented Mar 18, 2015 at 22:13 · Maybe I'm misunderstanding your first comment. Since the C program prints to the console without an issue, it's not being buffered. Therefore, I suspect Python is buffering output, hence the python -u.
🌐
Quora
quora.com › How-do-I-write-a-Python-script-to-run-a-C-program
How to write a Python script to run a C program - Quora
Answer (1 of 6): I assume you want to both compile and run the code! You can follow following steps: Since i am using windows to run the "gcc" command i did these settings: 1. Install DEV-CPP 2. Now set the path of "gcc" file in your environmental variables i.e. "C:\Program Files (x86)\Dev-Cpp\M...
Top answer
1 of 2
3

subprocess.run has optional stdout argument, you might give it file handle, so in your case something like

import subprocess
import sys
filestem = sys.argv[1]
with open('outputfile','wb') as f:
    subprocess.run(['/home/dev/executable_file', filestem],stdout=f)

should work. I do not have ability to test it so please run it and write if it does work as intended

2 of 2
0

You have several options:

NOTE - Tested in CentOS 7, using Python 2.7

1. Try pexpect:

"""Usage: executable_file argument ("ex. stack.py -lh")"""
import pexpect

filestem = sys.argv[1]
# Using ls -lh >> outputfile as an example
cmd = "ls {0} >> outputfile".format(filestem)
command_output, exitstatus = pexpect.run("/usr/bin/bash -c '{0}'".format(cmd), withexitstatus=True)
if exitstatus == 0:
    print(command_output)
else:
    print("Houston, we've had a problem.")

2. Run subprocess with shell=true (Not recommended):

"""Usage: executable_file argument ("ex. stack.py -lh")"""
import sys
import subprocess

filestem = sys.argv[1]
# Using ls -lh >> outputfile as an example
cmd = "ls {0} >> outputfile".format(filestem)
result = subprocess.check_output(shlex.split(cmd), shell=True)  # or subprocess.call(cmd, shell=True)
print(result)

It works, but python.org frowns upon this, due to the chance of a shell injection: see "Security Considerations" in the subprocess documentation.

3. If you must use subprocess, run each command separately and take the SDTOUT of the previous command and pipe it into the STDIN of the next command:

p = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE)
stdout_data, stderr_data = p.communicate()
p = subprocess.Popen(cmd, stdin=stdout_data, stdout=PIPE)
etc...

Good luck with your code!

Find elsewhere
🌐
howtos
wgilpin.com › howto › howto_cython.html
Running a C/C++ executable from within Python, without any IO | howtos
Now - Compile your executable, and then use the subprocess library. Then, in your Python script, use some variant of this: def test_no_io(): ''' Run a process that takes no input and produces no output ''' ## Shell=False helps the process terminate process = subprocess.Popen("./hello", shell=False) ## Get exit codes out, err = process.communicate() errcode = process.returncode print(errcode) process.kill() process.terminate()
🌐
DigitalOcean
digitalocean.com › community › tutorials › calling-c-functions-from-python
Calling C Functions from Python | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Readthedocs
reptate.readthedocs.io › developers › python_c_interface.html
Tutorial: Interfacing Python and C code — RepTate 1.4.0 documentation
Last steps, we need to modify the Python code. We make some addition to the file “basic_function_helper.py”. We need to: ... # Callback stuff from ctypes import CFUNCTYPE, POINTER def get_percent(percent): """Print advancement and set the next call when C has advanced a further 20%""" self.Qprint("Advancement of C calculations: %f%%" % (percent*100)) return percent + 0.2 CB_FTYPE_DOUBLE_DOUBLE = CFUNCTYPE(c_double, c_double) # define C pointer to a function type cb_get_percent = CB_FTYPE_DOUBLE_DOUBLE(get_percent) # define a C function equivalent to the python function "get_percent" basic_function_lib.def_python_callback(cb_get_percent) # the the C code about that C function
🌐
AskPython
askpython.com › python › examples › calling-python-scripts-from-c
Calling Python Scripts from C: A Step-by-Step Guide Using Python/C API - AskPython
April 10, 2025 - As C/C++ is more compatible with hardware and Python is easy for users to interact with, thus it opens different levels of opportunities. Further, it’s easy to call Python files in C because Python libraries help us create Python objects that can import files into multiple software. It comes with built-in functions to call methods into other source codes. Lastly, we can compile the whole C file by ‘cmake’ or use the ‘g++’ technique through the command prompt to get outputs.
🌐
DEV Community
dev.to › erikwhiting88 › how-to-use-c-functions-in-python-7do
How to Use C Functions in Python - DEV Community
August 4, 2019 - I'm at work now and can't really dig into it but if I get some time I'll let you know. ... Sure, thanks again! ... Not sure if this thread will be active again, but I found that on the c side of the program (using long long) it is accurate up to 20! . I found this by adding a printf statement in cfactorial.c . So it seems that at some point in the process of python and c communicating, the true value is lost.