Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create & read from tempfile

Tags:

python

Is there anyway I could write to tempfile and include it in a command, and then close/remove it. I would like to execute the command, eg: some_command /tmp/some-temp-file.
Many thanks in advance.

import tempfile temp = tempfile.TemporaryFile() temp.write('Some data') command=(some_command temp.name) temp.close() 
like image 859
DGT Avatar asked Mar 17 '11 19:03

DGT


People also ask

What is the synonym of create?

generate, produce, design, make, fabricate, fashion, manufacture, build, construct, erect, do, turn out. bring into being, originate, invent, initiate, engender, devise, frame, develop, shape, form, mould, forge, concoct, hatch. informal knock together, knock up, knock off.

What creat means?

Definition of creat (Entry 1 of 2) : an East Indian herb (Andrographis paniculata) having a juice that is a strong bitter tonic variously used in local medicine. creat- combining form. variants: or creato-

How did the word create?

"to bring into being," early 15c., from Latin creatus, past participle of creare "to make, bring forth, produce, procreate, beget, cause," related to Ceres and to crescere "arise, be born, increase, grow," from PIE root *ker- (2) "to grow." De Vaan writes that the original meaning of creare "was 'to make grow', which ...

What is the verb form for create?

create. verb. cre·​ate | \ krē-ˈāt \ created; creating.


Video Answer


1 Answers

Complete example.

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

Update: As mentioned in the comments, this may not work in windows. Use this solution for windows

Update 2: Python3 requires that the string to be written is represented as bytes, not str, so do instead

temp.write(bytes('Some data', encoding = 'utf-8'))  
like image 85
balki Avatar answered Sep 30 '22 12:09

balki