How to open a file in subprocess on mac osx

雨燕双飞 提交于 2019-12-11 11:22:04

问题


I want to open a file and wait the execution of next instruction till file is not closed. I followed the link How to open a file on mac OSX 10.8.2 in python python but it didn't work.

subprocess.call(['open','-W',FileName]) opens the file in texteditor, but executes next statement only when text-editor is quit from dock forcefully, even though I closed the opened file.Means, it should execute next statement only when file is closed, and then texteditor should automatically quit from dock.
I also tried with Popen but it didn't work

ss=subprocess.Popen("~/Downloads/DeletingDocs.txt",shell=True)
ss.communicate()   

Please suggest some method for it


回答1:


Try saving this as "EditOneAndQuit" and then do:

chmod +x EditOneAndQuit

Then start that from Python:

#!/bin/bash
# Start textedit in background
open "$1" &

# Wait till textedit has zero documents open
while true
do
sleep 1
docs=`osascript -e 'tell application "textedit" to get documents'`
if [ -z "$docs" ]; then
    # Kill off poor old textedit
    osascript -e 'tell application "textedit" to quit'
exit
fi
done

Try it from the shell first, by creating a document and editing it:

ls > fred.txt
./OpenOneAndQuit fred.txt

you should see that the script, along with textedit, exits when you close the document by clicking the red button.




回答2:


Closing the file does not end the process, as you will see that the editor is still running at the top of the screen when you close the file.

Press "Cmd+Q" to exit the process.

As it seems you cannot get your users to differentiate between closing documents and closing applications, I can only suggest something VERY UGLY. Can you start another background process that uses Applescript to wait till "textedit" starts, then ask "textedit" for a list of the documents it has open. Sleep for a few seconds if there are some, then check again. When there are none, it could tell "textedit" to exit and exit itself too.

The Applescript to do this looks like this.

tell app "TextEdit" to get documents

You may need to use "osascript" to get Python to execute Applescript.



来源:https://stackoverflow.com/questions/19689492/how-to-open-a-file-in-subprocess-on-mac-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!