Popen in main and subprocess

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Sat Jan 28 06:09:34 EST 2012


Am 28.01.2012 11:19 schrieb pistacchio:
> the following code (in the main thread) works well, I grep some files
> and the search until the first 100 results are found (writing the
> results to a file), then exit:
>
>      command = 'grep -F "%s" %s*.txt' % (search_string, DATA_PATH)
>
>      p = Popen(['/bin/bash', '-c', command], stdout = PIPE)

BTW: That's double weird: You can perfectly call grep without a shell 
in-between. And if you really needed a shell, you would use

     p = Popen(command, shell=True, stdout=PIPE)

- while the better solution is

     import glob
     command = ['grep', '-F', search_string] + glob.glob(DATA_PATH + 
'*.txt')
     p = Popen(command, stdout=PIPE)



> writing output: Broken pipe in the console:

It could be that this is an output of grep which tries to write data to 
its stdout. But you are only reading the first 100 lines, and 
afterwards, you close the pipe (implicitly).

Maybe you should read out everything what is pending before closing the 
pipe/dropping the subprocess.

BTW: I don't really understand

>                  if num_lines == 0:
>                      break
>                  else:
>                      break


HTH,


Thomas



More information about the Python-list mailing list