首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >linux中的Python子进程在文件存在时找不到文件

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

Stack Overflow用户
提问于 2015-04-17 19:48:45
回答 1查看 938关注 0票数 2

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

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

我查过文件了,它肯定在那里。

代码语言:javascript
复制
ll /projects/percid100_2/blastn.outfile
-rw-r--r-- 1  users 42633 Apr 17 12:34 /projects/percid100_2/blastn.outfile

以前的职能:

代码语言:javascript
复制
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)

发生功能错误:

代码语言:javascript
复制
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)

主要职能:

代码语言:javascript
复制
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是从以前的函数生成的,使用subprocess.Popen调用另一个程序。

我对这个问题的猜测是前面的命令已经完成,而且这个子进程调用不知怎么地没有识别出前一个函数的输出文件。我不知道该找什么解决办法。

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

但是,这是不行的。

我试着使用os.path.abspath(),没有办法解决这个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-17 20:03:52

我敢打赌,问题出在您描述的代码中,但还没有向我们展示,它运行的是生成grep正在寻找的文件的“以前的命令”。

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

然后,您需要几秒钟的时间才能在shell中查找文件,到那时,它已经创建了。所以这个错误看起来很令人困惑。

或者,如果您运行了几次程序,它最终会工作--要么是因为您运气好,要么是因为上次运行留下的文件是通过新运行找到的。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29708172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档