Ciasto piekarz Ciasto piekarz - 6 months ago 15
Python Question

how to wait until user quit text editor to take data to a variable using python?

In my Python command line tool I have a flag that I used to launch a text editor, but I want the terminal to wait until user has finished and exits the application and then pass on the text entered to a variable to be used later. I am guessing this can be done using a subprocess like below, but I am getting an error.

Code



pr = subprocess.Popen(sublime, stdin=diff.stdout)
while pr:
data = pr.stdout.read()
print data


Error




AttributeError: 'NoneType' object has no attribute 'read'.

Answer

SublimeText's command-line launcher has an optional flag (IIRC it's -w) that makes it wait until the user closes the window to return.

However, you should be aware that you can't simply read from the text editor's stdout. You need to provide it with a temporary file for the user to edit, and then read the data back from that temp file once the subl command exits.