2016-04-28 56 views
0

使用psutil模块我从那里检索正在运行的应用程序的列表,我检查这些应用程序的打开“.plist”文件。然后,我阅读'.plist'文件以获取当前在应用程序中打开的文档标题('NSTitle')。获取在OSX上打开的文档的名称(python)

有没有更好的/优化的方式来完成这个相同的任务?

import psutil 
import os 
import plistlib 


def check_files(application): 
    plist_original_path = "" 

    while True: 
     for i in psutil.process_iter(): 
      try: 
       if application in i.name(): 
        for j in i.open_files(): 
         if ".plist" in j.path: 
          plist_original_path = j.path 

      except psutil.ZombieProcess: 
       continue 
      except psutil.NoSuchProcess: 
       continue 

     try: 
      with open(plist_original_path, 'rb') as plist: 
       read_plist = plistlib.load(plist) 

      for i in read_plist: 
       try: 
        title = i["NSTitle"] 
        print(title) 
       except: 
        pass 

     except FileNotFoundError: 
      pass 

check_files("Excel") 

回答

0

我设法找到一个更好的方式使用苹果与python。

import subprocess 
import time 


x = '' 
while 1: 
    time.sleep(1) 

    with open('/Link/to/folder/app_script.txt', 'rb') as appscript: 
     x = appscript.read() 

    p = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    stdout, stderr = p.communicate(x) 

    x = stdout.split(b',') 

    print(x[0].decode().strip()) 
    print(x[1].decode().strip()) 
    print()