简体   繁体   中英

Run command line program from within Python

I am trying to run a blat search from within my python code. Right now it's written as...

os.system('blat database.fa fastafile pslfile')

When I run the code, I specify file names for "fastafile" and "pslfile"...

python my_code.py -f new.fasta -p test.psl

This doesn't work as "fastafile" and "pslfile" are variables for files created and named when I run the code, but if I were to use the actual file names I would have to go back and change my code each time I run it. I'd like to use the command line arguments above to specify the files.

How would I change this so that "fastafile" and "pslfile" will be replaced with my arguments (new.fasta and test.psl) each time?

You should make use of argparse to take in command line arguments (it'll give you variables with names f and p that hold the file names), then just form the command string from there.

command_str = "blat database.fa " + f + " " + p
os.system(command_str)

https://docs.python.org/3.4/library/argparse.html#argparse.ArgumentParser.parse_args

ArgumentParser.parse_args(args=None, namespace=None)

Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.

Previous calls to add_argument() determine exactly what objects are created and how they are assigned. See the documentation for add_argument() for details.

By default, the argument strings are taken from sys.argv, and a new empty Namespace object is created for the attributes.

import os

fastaFile = sys.argv[1]
pslFile = sys.argv[2]

os.system("blat -f {0} -p {1}".format(fastaFile,pslFile))

#example run: python scriptName.py fasta.txt psl.txt
#!/usr/bin/env python2.7

from sys import argv

def main():
    if len(argv) != 3:
        print "usage: ./my_code.py -f *.fasta -p *.psl"
        raise SystemExit
    os.system('blat database.fa {} {}'.format(*argv[1:]))

if __name__ == '__main__':
    main()

Instead of using os.system , it's considered more pythonic to use subprocess.call , which eliminates the need to sanitize the input from argv:

subprocess.call(['blat', 'database.fa', '-f', 'new.fasta', '-p', 'test.psl'])

You can also incorporate ApolloFortyNine's answer and use Python's great argparse module to get the arguments and pass them onto subprocess.call .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM