简体   繁体   中英

How do I open a document (eg. .txt) in another app from a Python Script mac

How and is it possible to open a document in a GUI text editor such as Word from a python script on a Mac? For example, do something like this:

Open x.txt in Word.app

Here is how you can do it on Mac OS:

If you want to open a file with a specific application on Mac OS, you do:

$ open -a appName fileName

So, for example you want to open hello.docx with Pages app, you do:

$ open -a pages path/hello.docx

Similarly to open a file with Word:

$ open -a "Microsoft Word.app" path/hello.docx

How you do it from Python (still only Mac OS):

Now, we need to be able to call shell commands from Python. There are several ways of doing it. You can see this question for a variety of ways.

One simple way of doing it would be:

>>> import os
>>> os.system('open -a "Microsoft Word.app" path/hello.docx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM