是否有我可以寫入tempfile並將其包含在一個命令中,然後關閉/刪除它。我想執行命令,例如:some_command/tmp/some-temp-file。
非常感謝提前。從tempfile創建和讀取
import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()
是否有我可以寫入tempfile並將其包含在一個命令中,然後關閉/刪除它。我想執行命令,例如:some_command/tmp/some-temp-file。
非常感謝提前。從tempfile創建和讀取
import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()
如果您需要一個名稱爲臨時文件,您必須使用NamedTemporaryFile
函數。那麼你可以使用temp.name
。詳情請參閱 http://docs.python.org/library/tempfile.html。
改爲使用NamedTemporaryFile
及其成員name
。由於Unix filesystems的工作方式,常規的TemporaryFile
甚至不能保證有名稱。
試試這個:
import tempfile
import commands
import os
commandname = "cat"
f = tempfile.NamedTemporaryFile(delete=False)
f.write("oh hello there")
f.close() # file is not immediately deleted because we
# used delete=False
res = commands.getoutput("%s %s" % (commandname,f.name))
print res
os.unlink(f.name)
它只是打印的內容臨時文件,但這應該給你正確的想法。請注意,在外部進程看到它之前,該文件已關閉(f.close()
)。這很重要 - 它確保所有的寫入操作都被正確刷新(並且在Windows中,您並未鎖定文件)。一旦關閉,通常會刪除NamedTemporaryFile
實例;因此delete=False
位。
如果您想要更多地控制過程,您可以嘗試subprocess.Popen
,但聽起來像commands.getoutput
可能就足夠您的目的。
這個答案(尤其是'delete = False'&'close()')是Windows情況下的關鍵信息。謝謝。 – meowsqueak 2016-07-22 06:02:09
完整的例子。
import tempfile
with tempfile.NamedTemporaryFile() as temp:
temp.write('Some data')
if should_call_some_python_function_that_will_read_the_file():
temp.seek(0)
some_python_function(temp)
elif should_call_external_command():
temp.flush()
subprocess.call(["wc", temp.name])
更新:由於在評論中提到的,這可能無法工作在Windows中。使用this解決方案的窗口
只是想補充一點,如果命令被一些Python代碼(如函數調用)所替代,請確保您執行temp.seek(0),因此如果該函數嘗試讀取內容,它將不會空手。 – Fortepianissimo 2013-03-19 20:39:34
+1用於_with_。是否有理由說明[documentation](https://docs.python.org/2/library/tempfile.html)中的示例不使用_with_? – cbare 2014-10-01 19:34:50
確保你從[docs](https://docs.python.org/3.4/library/tempfile.html#tempfile.NamedTemporaryFile)中考慮到這一點:「是否可以使用該名稱第二次打開該文件,雖然指定的臨時文件仍處於打開狀態,但各個平臺*之間會有所不同(它可以在Unix上使用;不能在Windows NT或更高版本中使用)。「請注意,當您調用'command'時,使用'with'語句會使tempfile保持打開狀態,因此您的代碼的可移植性會受到影響。 – Jens 2015-02-17 19:22:00
請確保您在傳遞給some_command – balki 2012-02-22 14:17:56
@balki之前刷新文件,或者您可以傳遞'bufsize = 0'來使其無緩衝。 – 2016-03-24 17:59:20