| 1 |
# Public domain notice for all NCBI EDirect scripts is located at: |
| 2 |
# https://www.ncbi.nlm.nih.gov/books/NBK179288/#chapter6.Public_Domain_Notice |
| 3 |
|
| 4 |
# Authors: Jonathan Kans, Aaron Ucko |
| 5 |
|
| 6 |
import subprocess |
| 7 |
import shlex |
| 8 |
|
| 9 |
def execute(cmmd, data=""): |
| 10 |
# the cmmd argument accepts either a flat string: |
| 11 |
# "efetch -db nuccore -id NM_000518.5 -format fasta" |
| 12 |
# or a sequence of strings: |
| 13 |
# ('efetch', '-db', 'nuccore', '-id', 'NM_000518.5', '-format', 'fasta') |
| 14 |
if isinstance(cmmd, str): |
| 15 |
cmmd = shlex.split(cmmd) |
| 16 |
res = subprocess.run(cmmd, input=data, |
| 17 |
capture_output=True, |
| 18 |
encoding='UTF-8') |
| 19 |
return res.stdout.strip() |
| 20 |
|
| 21 |
def pipeline(cmmds, data=""): |
| 22 |
# the cmmds argument accepts either a flat string with piped commands: |
| 23 |
# '''efetch -db nuccore -id NM_000518.5 -format gbc | xtract -insd CDS gene product''' |
| 24 |
# or a sequence of individual shell command strings to be joined with pipe symbols: |
| 25 |
# ('efetch -db nuccore -id NM_000518.5 -format gbc', 'xtract -insd CDS gene product') |
| 26 |
# or a mixture of strings and sequences of strings: |
| 27 |
# ('efetch -db nuccore -id NM_000518.5 -format gbc', |
| 28 |
# ('xtract', '-insd', 'CDS', 'gene', 'product', 'feat_location')) |
| 29 |
# use "sys.stdin.read()" as the second argument to relay data piped to the script |
| 30 |
def flatten(cmmd): |
| 31 |
if isinstance(cmmd, str): |
| 32 |
return cmmd |
| 33 |
else: |
| 34 |
return shlex.join(cmmd) |
| 35 |
if not isinstance(cmmds, str): |
| 36 |
cmmds = ' | '.join(map(flatten, cmmds)) |
| 37 |
res = subprocess.run(cmmds, input=data, shell=True, |
| 38 |
capture_output=True, |
| 39 |
encoding='UTF-8') |
| 40 |
return res.stdout.strip() |
| 41 |
|
| 42 |
def efetch(*, db, id, format, mode=""): |
| 43 |
# the efetch shortcut requires the use of named arguments: |
| 44 |
# (db="nuccore", id="NM_000518.5", format="fasta") |
| 45 |
cmmd = ('efetch', '-db', db, '-id', str(id), '-format', format) |
| 46 |
if mode: |
| 47 |
cmmd = cmmd + ('-mode', mode) |
| 48 |
return execute(cmmd) |