Python: call piped commands using subprocess








For example, I want to call external command:
cat /tmp/fruits.txt | grep apple
, depending on if the input is trusted or not, we have the following two options:
  • For untrusted input:
    import subprocess
    
    cat = subprocess.popen(['/bin/cat', '/tmp/fruits.txt'], stdout=PIPE)
    grep = subprocess.popen(['/bin/grep', 'apple'], stdin=cat.stdout, stdout=PIPE)
    cat.stdout.close()
    output = grep.communicate()[0]
    print output
    
    
  • For trusted input, you can simply set shell=True:
    import subprocess
    
    output=subprocess.check_output('cat /tmp/fruits.txt | grep apple', shell=True)
    print output
    
    



No comments:

Post a Comment