Run Python3 From C
----------------
Written by:
Stephen Andersen
Group 8
Winter 2016
----------------
Introduction
This tutorial or 'app note' will demonstrate how to run python3 from C
This tutorial expects you to understand basic C and Python3.
C Side
SETUP FOR SIGNAL HANDLING
// Have a bool to ensure that if the signal activates, C will notice (Python can be FAST)
bool sig_flag = false;
...
// Init signal handler for first use
sig_handler(0);
SIGNAL HANDLER
void sig_handler(int sig) {
// We have resumed.
// Re-init signal handler
signal(SIGCONT, sig_handler);
sig_flag = true;
return;
}
SOMEWHERE ELSE IN CODE
// Here we write the command to start python into a string
sprintf(buffer, "python3 GA_Code/main.py -p %d", getpid());
// The passing of the pid is important only if you pause for pythons result (via pipelining)
// This runs the string in bash
system(buffer);
// WAIT FOR OUTPUT (A SIGNAL FROM PYTHON'S KILL())
// If sig_flag is already true, python finished really fast; no need for pause()
if (!sig_flag)
// Pause() will make C stop executing until killed
pause();
// Reset sig_flag
sig_flag = false;
Python Side
SIGNAL HANDLING
def alert_parent_program(pid):
"""
Inputs: pid (the pid of the program that called this code)
Outputs: a SIGCONT signal to the process with the matching pid
"""
if pid is not None:
system("kill -CONT " + str(pid))