execute shell script from python, needs sys.argv

Peter Otten __peter__ at web.de
Thu Nov 4 17:11:06 CET 2010

Matt wrote:

> I am trying to execute a shell script from within python..  This shell
> script takes the format, where $1 and $2 are variables from the
> command line: cat $1 | Fastx_trimmer -n COUNT -o $2
> straight into the cmd line it would be:  cat file.1 | Fastx_trimmer -n
> COUNT -o file.2
> So,  know that there is a way to do this in python using the
> subprocess module, but despite a lot of effort, I can't seem to get
> this to work, and precisely because of those arguments taken from the
> command line.
> I was thinking that the easiest thing to so was to
> import sys, os, subprocess
> proc = subprocess.call([cat sys.argv[1] | fastx_trimmer -n COUNT -o
> sys.argv[2]], shell=True)
> this clearly does not work...
> alternatively, I could put the shell command in its own file, say
> fastx.sh, and pass it's arguments to it vie the command line.
> import sys, os, subprocess
> proc = subprocess.call([fastx.sh, sys.argv[1], sys.argv[2]],
> shell=True)
> But, this does not seem to work as this is not the proper way to pass
> arguments to the shell script.
> in short, I'm sure that this is a easy fix, but given my still limited
> python vocabulary, it eludes me.

You could do it in two steps:

>>> from subprocess import *
>>> source = Popen(["cat", "/usr/share/dict/words"], stdout=PIPE)
>>> call(["wc"], stdin=source.stdout)
  98569   98568  931708

A similar example is here, under a "can't miss" headline:



More information about the Python-list mailing list