create & read from tempfile

前端 未结 4 1853
难免孤独
难免孤独 2020-12-09 01:17

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.

4条回答
  •  不思量自难忘°
    2020-12-09 01:51

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

提交回复
热议问题