Search code examples
pythoncallfile-io

How can I call/run a software by python?


I'm trying to make a simple script to run different tasks one by one (one after another) but I don't know how can I run the program by python script! I know that it should be simple! but I couldn't find it any where. my example is this:

samtools merge filename.bam file1.sorted.bam file2.sorted.bam file3.sorted.bam file4.sorted.bam

samtools index filename.bam 
samtools idxstats filename.bam > filename.txt 
samtools pileup -vcf path/filename.fa filename_sorted.bam

I want the python to run the first command and after its finished then goes to the next one! it's important that it wait's until it's finished!


Solution

  • from subprocess import call # call runs an external program and waits for it to quit
    
    for command in ("samtools merge filename.bam file1.sorted.bam file2.sorted.bam file3.sorted.bam file4.sorted.bam", 
                    "samtools index filename.bam", 
                    "samtools idxstats filename.bam > filename.txt", 
                    "samtools pileup -vcf path/filename.fa filename_sorted.bam"):
        # shell=True is so you can handle redirects like in the 3rd command
        call(command, shell=True)