'Problem of running samtools in python using subprocess.run()

I'm using subprocesss.run() to run samtools command in python. The code is as below:

result = subprocess.run(['samtools', 'faidx', 'hg38.fa.gz', 'chr1:169699712-169699719'], check=True, stdout = subprocess.PIPE)

and I got the following problem:

CalledProcessError: Command '['samtools', 'faidx', 'hg38.fa.gz', 'chr1:169699712-169699719']' died with <Signals.SIGABRT: 6>.

The samtools command ran successfully in terminal, but failed in subprocess.run.

Does anyone know the cause of the bug? Thank you so much.



Solution 1:[1]

Maybe try with this code, I use a similar one to run commands with bwa, samtools and others without issues so far:

import subprocess

def run(cmd) :
   proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   proc.communicate()

cmd = "samtools faidx /path/to/file.fa.gz" # change for desired command line here
run(cmd)

Solution 2:[2]

Try the command below:

P1 = subprocess.run('samtools faidx hg38.fa.gz chr1:169699712-169699719', capture_output=True, text=True, shell=True)
print(P1.returncode) # will show 0 if execution is successful
print(P1.stdout) # will contain the output in str format

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AnHo
Solution 2 Rafeed