Python subprocess communication

Cheatsheet - Python subprocess communication Link to heading

Imports Link to heading

from subprocess import Popen, PIPE

Imports for signals Link to heading

import signal, os

Start process Link to heading

process = Popen(['./sum 50'], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

Check if process is alive Link to heading

def isAlive(process):
	poll = process.poll()
	if poll == None:
		print("Program running...")
	else:
		print("Program stopped :(")

Read from stdout Link to heading

def getline(process):
	return "stdout : " + process.stdout.readline().decode('utf-8')

Write to stdin Link to heading

process.stdin.write((str(i)+"\n").encode())
process.stdin.flush()

Send signals Link to heading

os.kill(process.pid, signal.SIGSTOP)

Available signals :

{.table .pure-table .table-striped .table-responsive}

Id Name Description
1 SIGHUP Exit Hangup
2 SIGINT Exit Interrupt
3 SIGQUIT Core Quit
4 SIGILL Illegal Instruction
5 SIGTRAP Trace/Breakpoint Trap
6 SIGABRT Core Abort
7 SIGEMT Emulation Trap
8 SIGFPE Arithmetic Exception
9 SIGKILL Exit Killed
10 SIGBUS Bus Error
11 SIGSEGV Segmentation Fault
12 SIGSYS Bad System Call
13 SIGPIPE Broken Pipe
14 SIGALRM Alarm Clock
15 SIGTERM Exit Terminated
16 SIGUSR1 User Signal 1
17 SIGUSR2 User Signal 2
18 SIGCHLD Child Status
19 SIGPWR Power Fail/Restart
20 SIGWINCH Window Size Change
21 SIGURG Urgent Socket Condition
22 SIGPOLL Socket I/O Possible
23 SIGSTOP Stopped (signal)
24 SIGTSTP Stopped (user)
25 SIGCONT Ignore Continued
26 SIGTTIN Stopped (tty input)
27 SIGTTOU Stopped (tty output)
28 SIGVTALRM Virtual Timer Expired
29 SIGPROF Profiling Timer Expired
30 SIGXCPU CPU time limit exceeded
31 SIGXFSZ File size limit exceeded
32 SIGWAITING All LWPs blocked
33 SIGLWP Virtual Interprocessor Interrupt for Threads Library
34 SIGAIO Asynchronous I/O

Full code example Link to heading

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv){
	
	int sum, tmp, i;

	sum = atoi(argv[1]);
	printf("initial sum :%d\n", sum);

	for(i=0;i<5;i++){
		printf("Nb :\n");
		fflush(stdout);
		scanf("%d",&tmp);
		sum += tmp ;
	}

	printf("\nSum : %d", sum);
	return 0 ;
}
#!/usr/bin/env python3
from subprocess import Popen, PIPE
import signal, os

def isAlive(process):
	poll = process.poll()
	if poll == None:
		print("Program running...")
	else:
		print("Program stopped :(")

def getline(process):
	return "stdout : " + process.stdout.readline().decode('utf-8')


process = Popen(['./sum 50'], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

print(getline(process))

for i in range(1,6):
	print(getline(process))
	print("write " + str(i))
	process.stdin.write((str(i)+"\n").encode())
	process.stdin.flush()

	
print(getline(process))
print(getline(process))
		

#Stop/resume process
# os.kill(process.pid, signal.SIGSTOP)
#os.kill(process.pid, signal.SIGCONT)