在python

时间:2016-01-13 22:37:36

标签: python bash flags

我目前正在python中编写一个带有许多标志的脚本。这是我第一次尝试这样的程序,我从bash脚本中得到了一个我不太了解的输出。例如,当我在bash shell中运行脚本时:

$ python my_script.py -f <input_file.txt> -k <test_string> -c <user_input>

我在脚本的输出之前得到了这个输出:

usage: rm [-f | -i] [-dPRrvW] file ...
       unlink file

我似乎无法摆脱这种情况,这对输出的美观感到沮丧。任何帮助都会很棒!

我使用的代码:

import sys, getopt, re, subprocess, collections, itertools

def find_kmers( arguments=sys.argv[1:] ):

    required_opts = ['-f','-c','-k']



    opts, args = getopt.getopt(arguments,'f:k:c:')



    opt_dic = dict(opts)



    for opt in required_opts:

        if opt not in opt_dic:

            return "incorrect arguments, please format as: python_script.py -f <filename> -k <kmer> -c <chromosome_name>"



    def rev_comp(sequence):

        reversed_dic = {'A':'T','T':'A','C':'G','G':'C'}

        return ''.join(reversed_dic[_] for _ in sequence[::-1])



    kmer = opt_dic['-k']

    subprocess.call(['bash','-c',"grep '>' S288C_R64.fasta > grep.tmp"])

    chromosomes = [_[1:].strip() for _ in open('grep.tmp')]

    subprocess.call(['bash','-c','rm','grep.tmp'])

    found = False

    if any(opt_dic['-c']==_ for _ in chromosomes):

        found = True



    def get_sequence(file):

        sequence = ''

        for line in file:

            if line.startswith('>'): break

            sequence += line.strip()

        return sequence.upper()



    ofile = open(opt_dic['-f'])

    if found == True:

        for line in ofile:

            if line.startswith('>'):

                if line[1:].strip() == opt_dic['-c']:

                    sequence = get_sequence(ofile)

                    break



    else:

        return 'chromosome not found in %s. \n chromosomes in file are:%s'%(opt_dic['-f'],', '.join(str(_) for _ in chromosomes))





    kmer_matches1 = re.finditer('(?=%s)'%opt_dic['-k'],sequence)

    kmer_matches2 = re.finditer('(?=%s)'%opt_dic['-k'],rev_comp(sequence))







    def print_statement(start,strand):



        return '%s\thw1_script\tkmer=%s\t%s\t%s\t.\t%s\t.\tID=S288C;Name=S288C\n'%(opt_dic['-c'],opt_dic['-k'],start,start+len(opt_dic['-k'])-1,strand)



    pos_strand = collections.deque()

    neg_strand = collections.deque()

    for match1,match2 in itertools.izip(kmer_matches1,kmer_matches2):

        pos_strand.append(match1.start()+1)

        neg_strand.append(match2.start()+1)



    wfile = open('answer.gff3','w')

    while len(pos_strand)>0 and len(neg_strand)>0:

        if pos_strand[0]<neg_strand[0]:

            start = pos_strand.popleft()

            wfile.write(print_statement(start,'+'))

        else:

            start = neg_strand.popleft()

            wfile.write(print_statement(start,'-'))



    while len(pos_strand)>0:

        start = pos_strand.popleft()

        wfile.write(print_statement(start,'+'))



    while len(neg_strand)>0:

        start = neg_strand.popleft()

        wfile.write(print_statement(start,'-'))



    wfile.close()



    return 'percent-GC = %s'%str(sum(sequence.count(gc) for gc in ["G","C"])/float(len(sequence)))



if __name__ == '__main__':

    print find_kmers()

1 个答案:

答案 0 :(得分:3)

调用subprocess.call(['bash','-c','rm','grep.tmp']) 一行代码要求bash命令为单个字符串。变化:

subprocess.call(['bash', '-c', 'rm grep.tmp'])

为:

os.unlink('grep.tmp')  # Or os.remove; same thing, different names

或者,更合理的是,不要使用子进程,只需执行:

def find_kmers( arguments=sys.argv[1:] ):
    required_opts = ['-f','-c','-k']

    opts, args = getopt.getopt(arguments,'f:k:c:')

    opt_dic = dict(opts)

    for opt in required_opts:
        if opt not in opt_dic:
            return "incorrect arguments, please format as: python_script.py -f <filename> -k <kmer> -c <chromosome_name>"

    def rev_comp(sequence):
        reversed_dic = {'A':'T','T':'A','C':'G','G':'C'}
        return ''.join(reversed_dic[_] for _ in sequence[::-1])

    kmer = opt_dic['-k']
    # Replaces grep with temp file with trivial Python equivalent
    with open('S288C_R64.fasta') as f:
        chromosomes = [line[1:].strip() for line in f if '>' in line]

    # No need for any loop when just checking for exact value
    if opt_dic['-c'] not in chromosomes:
        return 'chromosome not found in %s. \n chromosomes in file are:%s'%(opt_dic['-f'],', '.join(str(_) for _ in chromosomes))


    def get_sequence(file):
        sequence = ''
        for line in file:
            if line.startswith('>'): break
            sequence += line.strip()
        return sequence.upper()

    with open(opt_dic['-f']) as ofile:
        for line in ofile:
            if line.startswith('>'):
                if line[1:].strip() == opt_dic['-c']:
                    sequence = get_sequence(ofile)
                    break


    kmer_matches1 = re.finditer('(?=%s)'%opt_dic['-k'],sequence)
    kmer_matches2 = re.finditer('(?=%s)'%opt_dic['-k'],rev_comp(sequence))

    def print_statement(start,strand):
        return '%s\thw1_script\tkmer=%s\t%s\t%s\t.\t%s\t.\tID=S288C;Name=S288C\n'%(opt_dic['-c'],opt_dic['-k'],start,start+len(opt_dic['-k'])-1,strand)

    pos_strand = collections.deque()
    neg_strand = collections.deque()
    for match1,match2 in itertools.izip(kmer_matches1,kmer_matches2):
        pos_strand.append(match1.start()+1)
        neg_strand.append(match2.start()+1)

    with open('answer.gff3','w') as wfile:
        while pos_strand and neg_strand:
            if pos_strand[0]<neg_strand[0]:
                start = pos_strand.popleft()
                wfile.write(print_statement(start,'+'))
            else:
                start = neg_strand.popleft()
                wfile.write(print_statement(start,'-'))

        for start in pos_strand:
            wfile.write(print_statement(start,'+'))
        for start in neg_strand:
            wfile.write(print_statement(start,'-'))

    return 'percent-GC = %s'%str(sum(sequence.count(gc) for gc in ["G","C"])/float(len(sequence)))

更快,更不容易出错。

事实上,所有的子进程使用都可以用真正的Python代码替换,并且它会大大改善它(并且大部分Python代码也会简化):

add()