Reputation: 5056
I need to call bash from python script and store result in the variable (the output is one number).
I need
output = subprocess.call('command', shell=True)
with command replaced by output from my bash one-liner which looks like this:
cat file.sam | grep -v "@" | grep "gi|519666810|ref|NM_001278619.1|" | perl -lane '$l = 0; $F[5] =~ s/(\d+)[MX=DN]/$l+=$1/eg; print $l' | awk '{ sum+=$1} END {print sum}'
I know that simple commands work just fine:
output = subprocess.check_output("echo 122;", shell=True)
My problem is that instead of 122 I need value from my bash one-liner. And it would be perfect if I didn't need to reformat it and could use it just as is.
Here are my attempts:
output = subprocess.check_output("cat file.sam | grep -v "@" | grep "gi|519666810|ref|NM_001278619.1|" | perl -lane '$l = 0; $F[5] =~ s/(\d+)[MX=DN]/$l+=$1/eg; print $l' | awk '{ sum+=$1} END {print sum}'
", shell=True)
File "script.py", line 9
output = subprocess.check_output("cat file.sam | grep -v "@" | grep "gi|519666810|ref|NM_001278619.1|" | perl -lane '$l = 0; $F[5] =~ s/(\d+)[MX=DN]/$l+=$1/eg; print $l' | awk '{ sum+=$1} END {print sum}'
^
SyntaxError: invalid syntax
Attempt two:
output = subprocess.check_output("cat file.sam | grep -v \"@\" | grep \"gi|519666810|ref|NM_001278619.1|\" | perl -lane '$l = 0; $F[5] =~ s/(\d+)[MX=DN]/$l+=$1/eg; print $l' | awk '{ sum+=$1} END {print sum}'
", shell=True)
File "script.py", line 9
output = subprocess.check_output("cat file.sam | grep -v \"@\" | grep \"gi|519666810|ref|NM_001278619.1|\" | perl -lane '$l = 0; $F[5] =~ s/(\d+)[MX=DN]/$l+=$1/eg; print $l' | awk '{ sum+=$1} END {print sum}'
^
SyntaxError: EOL while scanning string literal
Upvotes: 0
Views: 487
Reputation: 5056
Thanks for help! Finally, this works:
command = "cat file.sam | grep -v \"@\" | grep \"gi|519666810|ref|NM_001278619.1|\" | perl -lane '$l = 0; $F[5] =~ s/(\d+)[MX=DN]/$l+=$1/eg; print $l' | awk '{ sum+=$1} END {print sum}'";
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
#Launch the shell command:
output = process.communicate()[0];
Upvotes: 1