Local Hero
Local Hero

Reputation: 503

Redirect stdin input to a file for a thread process in python

I have a script in python that create a thread that execute an external program with "subprocess" module. Now, this external program is very simple, take a number from stdin and print:

#include <stdio.h>

main(){
  int numero;

  printf("Inserisci numero: ");
  scanf("%d",&numero);

  switch(numero){
    case 1:
        printf("uno\n");
        break;
    case 2:
        printf("due\n");
        break;
    default:
        printf("caso default\n");
  }

}

Now, I have wrote a script in python that take the input from a text file; the script is running in the follow mode:

 python filtro.py ./a.out test.txt

and the script is the follow:

import sys
import subprocess
import threading
import fileinput

class Filtro:
  #Costruttore
  def __init__(self,cmd):
    #Funzione di esecuzione thread
    def exec_cmd():
        try:
            subprocess.check_call(cmd, shell=True)
        except subprocess.CalledProcessError:
            print "Il comando", cmd, "non esiste. Riprovare."


    #Generazione thread demone
    self.thr=threading.Thread(name="Demone_cmd",target=exec_cmd)
    self.thr.setDaemon(True)
    self.thr.start()

  def inp(self,txt):
    for line in fileinput.input(txt):
        print line

filtro=Filtro(sys.argv[1])
filtro.inp(sys.argv[2])

The trouble is that the input from the file is ignored and the output is this:

[vbruscin@lxplus0044 python]$ python filtro.py ./a.out test.txt
1

2

3
Inserisci numero: [vbruscin@lxplus0044 python]$ caso default

What's the problem? Thanks to all for the help.

Upvotes: 3

Views: 722

Answers (1)

jwilner
jwilner

Reputation: 6606

You're assuming that your python's stdout is your subprocess' stdin, which isn't true. Check out the documentation for subprocess: https://docs.python.org/2/library/subprocess.html. I believe for your situation you can use popen, passing an open file object for stdin, write your arguments to that file object, and then use communicate to get the result.

I'll add that I suspect this process is over complicated for what you need, but the example must only be an example, so it's hard to say the degree to which it's really over complicated.

Upvotes: 1

Related Questions