简体   繁体   English

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

[英]Python: pass to subprocess a temporary generated file not as the last argument

how to use subprocess if my temp-file argument is in the middle of the command?如果我的临时文件参数在命令中间,如何使用子进程? For example a terminal command looks like this:例如,终端命令如下所示:

program subprogram -a -b tmpFILE otherFILE

I tried variations of this:我尝试了以下变体:

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()

or或者

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

but nothing works... My temporary generated file in python shouldn't be as the last parameter.但没有任何效果......我在python中临时生成的文件不应该作为最后一个参数。

Thanks谢谢

Is there a reason to use SpooledTemporaryFile instead of other types of temp file?是否有理由使用SpooledTemporaryFile而不是其他类型的临时文件? If not, I recommend using NamedTemporaryFile as you can retrieve the name from it.如果没有,我建议使用NamedTemporaryFile因为您可以从中检索名称。 I have tried to retrieve the name from SpooledTemporaryFile and got '<fdopen>' which does not seem to be valid.我试图从SpooledTemporaryFile检索名称并得到'<fdopen>'这似乎无效。

Here is the suggested code:这是建议的代码:

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()

Discussion讨论

  • Using the with statement, you don't have to worry about closing the file.使用 with 语句,您不必担心关闭文件。 As soon as the with block is finished, the file is automatically closed.一旦 with 块完成,文件就会自动关闭。
  • Instead of calling seek , you should call flush to commit your file buffer to disk before calling program .在调用program之前,您应该调用flush来将文件缓冲区提交到磁盘,而不是调用seek

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM