Skip to main content
 首页 » 编程设计

python之NamedTemporaryFile 存在,但外部程序无法访问它

2024年10月24日10xxx_UU

这是对 this question 的后续跟进关于使用 NamedTemporaryFile()

我有一个创建和写入临时文件的函数。然后我想在另一个函数中使用该文件,该函数调用使用该文件的终端命令(该程序来自 Blast+ 套件,blastn)。

def db_cds_to_fna(collection="genes"):  # collection gets data from mongoDB 
 
    tmp_file = NamedTemporaryFile() 
    # write stuff to file 
 
    return tmp_file 
 
def blast_all(blast_db, collection="genes"):         
 
    tmp_results = NamedTemporaryFile()     
    db_fna = db_cds_to_fna(collection) # should return another file object 
 
    Popen( 
        ['blastn', 
         '-query', db_fna.name, 
         '-db', blast_db, 
         '-out', tmp_results.name, 
         '-outfmt', '5']  # xml output 
    ) 
 
    return tmp_results 

当我调用 blast_all 时,我从 blastn 命令中得到一个错误:

Command line argument error: Argument "query". File is not accessible:  `/var/folders/mv/w3flyjvn7vnbllysvzrf9y480000gn/T/tmpAJVWoz' 

但是,就在 Popen 调用之前,如果我执行 os.path.isfile(db_fna.name) 它的计算结果为 True .我也可以做

print Popen(['head', db_fna.name]).communicate(0) 

它正确地吐出文件的第一行。所以文件存在,并且是可读的。此外,我使用相同的策略从相同的 blast+ 套件调用不同的程序(makeblastdb,请参阅顶部链接的问题)并且它有效。权限可能有问题吗?如果文件不存在,FWIW blastn 会返回相同的错误,但很明显我正在正确创建文件,并且当我调用 Popen 时它是可读的,所以我很难过。

请您参考如下方法:

我认为问题可能是操作系统没有将文件同步到磁盘。写入文件描述符后执行:

tmp_file.flush() 
os.fsync(tmp_file) 

https://docs.python.org/3/library/os.html#os.fsync