我需要从python脚本调用bash并将结果存储在变量中(输出是一个数字)。
我需要
output = subprocess.call('command', shell=True)
将命令替换为我的bash one-liner的输出,如下所示:
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}'
我知道简单的命令可以正常工作:
output = subprocess.check_output("echo 122;", shell=True)
我的问题是,而不是 122 我需要从我的bash one-liner获得价值。如果我不需要重新格式化它并且只能 那么它将是完美的。
以下是我的尝试:
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
尝试二:
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
答案 0 :(得分:1)
感谢您的帮助!最后,这有效:
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];