Skip to main content
 首页 » 编程设计

Python:传递给子进程一个临时生成的文件而不是最后一个参数

2024年10月17日5cloudgamer

如果我的临时文件参数在命令中间,如何使用子进程?例如,终端命令如下所示:

program subprogram -a -b tmpFILE otherFILE 

我试过这个的变体:

from subprocess import Popen, PIPE 
from tempfile import SpooledTemporaryFile as tempfile 
tmpFILE=tempfile() 
tmpFILE.write(someList) 
tmpFILE.seek(0) 
print Popen(['program','subprogram', '-a', '-b', otherFile],stdout=PIPE,stdin=tmpFILE).stdout.read() 
f.close() 

或

print Popen(['program','subprogram', '-a', '-b', tmpFILE, otherFile],stdout=PIPE,stdin=tmpFILE).stdout.read() 

但没有任何作用...我在 python 中临时生成的文件不应该作为最后一个参数。

谢谢

请您参考如下方法:

有理由使用SpooledTemporaryFile吗?而不是其他类型的临时文件?如果没有,我建议使用 NamedTemporaryFile因为您可以从中检索名称。我试图从 SpooledTemporaryFile 中检索名称得到了'<fdopen>'这似乎无效。

这里是建议的代码:

from subprocess import Popen, PIPE 
import tempfile 
 
with tempfile.NamedTemporaryFile() as temp_file: 
    temp_file.write(someList) 
    temp_file.flush() 
    process = Popen(['program', 'subprogram', '-a', '-b', temp_file.name, otherFile], stdout=PIPE, stderr=PIPE) 
    stdout, stderr = process.communicate() 

讨论

  • 使用 with 语句,您不必担心关闭文件。 with block 完成后,文件将自动关闭。
  • 而不是调用 seek , 你应该调用 flush在调用 program 之前将文件缓冲区提交到磁盘.