Redirect stdin input to file for stream process in python

I have a script in python that creates a thread that executes an external program with the subprocess module. Now this external program is very simple, take the 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 written a script in python that takes input from a text file; The script runs in the following mode:

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

      

and the script is:

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 problem is that the input from the file is ignored and the output is:

[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 everyone for the help.

+3


source to share


1 answer


You are assuming your python stdout is your 'stdin subprocess, which is not correct. Check the documentation for subprocess: https://docs.python.org/2/library/subprocess.html . I believe for your situation, you can use popen by passing the open file to stdin, writing your arguments to that file object, and then using the link to get the result.



I'll add that I suspect the process is too complicated for what you need, but the example should only be an example, so it's hard to tell how difficult it really is.

+1


source







All Articles