linux中的Python子进程在文件存在时找不到文件

2024-06-17 08:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

这个虫子快把我逼疯了。 脚本的错误输出:

>>>Run shell cmd "grep -vw ^# *.blastn | awk $1 != $2 > *matchfile*"
grep: /projects/percid100_2/blastn.outfile: No such file or directory
2

我一定查过档案了。在

^{pr2}$

上一功能:

def run_blastn(outdir, outfile):
    """Run blastn under given percent identity """
    print ">>> Run blastn"
    blastnlog = os.path.join(outdir, 'blastn_db_log')
    # make database and run blastn 
    ref = Popen(['cmd1', '-logfile', blastnlog])
    ref.communicate()
    blastn = Popen(['cmd2', '-out', outfile], stderr=PIPE)

出现函数错误:

def filter_query(infile, matchfile):
    """Filter out self to self hit and no hit"""
    print ">>> Filter query self to self hit and no hit"
    print('>>> Run shell cmd "grep -vw ^# *.blastn | awk $1 != $2 > *matchfile*"')
    grep = Popen(['grep', '-vw', '^#', infile], stdout=PIPE)
    awk = Popen(['awk', '$1 != $2'], stdin=grep.stdout, stdout=PIPE)
    output = awk.communicate()[0]
    grep.communicate()
    if grep.returncode != 0:
        print grep.returncode
        sys.exit()

    with open(matchfile, 'wb') as ofile:
        print 'Write to file %s' % matchfile
        ofile.write(output)

主要功能:

def main():
    parser = get_parser()
    args = parser.parse_args()
    if not os.path.exists(args.outdir):
        os.makedirs(args.outdir)
    outdir = os.path.abspath(args.outdir)

    bloutfile = 'blastn.outfile'
    path_bloutfile = os.path.join(outdir, bloutfile)

    # filter query seq outfile name 
    matchfile = 'match_file'
    path_matchfile = os.path.join(outdir, matchfile)

    # run blastn 
    run_blastn(outdir, path_bloutfile)
    # filter blastn output gain only matching information 
    filter_query(path_bloutfile, path_matchfile)

if __name__=='__main__':
    main()

其中一个函数输入infile是由调用另一个程序的上一个函数use subprocess.Popen生成的。在

我对这个问题的猜测是上一个命令完成了,不知何故这个子进程调用没有识别上一个函数的输出文件。我不知道该怎么解决。在

如果我再尝试运行脚本几次,脚本最终将成功运行。在

然而,这是不好的。在

我试图使用os.path.abspath(),但没有解决这个问题的运气。在


Tags: path函数runosargsgrepoutfileprint
1条回答
网友
1楼 · 发布于 2024-06-17 08:39:15

我敢打赌,问题出在您描述的代码中,但是还没有展示给我们,它运行“previous command”来生成grep正在查找的文件。在

如果您通过创建一个Popen来运行前一个命令,但是没有wait,那么它仍然会在后台运行。如果启动grep太快,则文件可能尚未创建。所以你得到了错误。在

然后,您需要几秒钟的时间在shell中查找该文件,此时,已经创建了。所以这个错误看起来令人费解。在

或者,如果你运行了几次程序,最终它会工作,要么是因为你的计时很幸运,要么是因为上一次运行留下的文件被新运行找到了。在

修复方法可能只是添加一个丢失的other_command.communicate(),但是如果没有看到其他代码,就很难确定。在

相关问题 更多 >