【问题标题】:Open text file and search on OS X在 OS X 上打开文本文件并搜索
【发布时间】:2015-04-12 02:28:36
【问题描述】:

我想打开一个文本文件,然后立即搜索某个字符串并突出显示它。

我用:

command ="open "+'"'+ file +'"'
os.system(command)

但我想要类似的东西:

command ="open "+'"'+ file +'"' + "then"+ "ctrl-F(string)"

显然这不起作用,但有没有办法做到这一点?我只想像普通 CTRL+F 一样突出显示字符串中的文本。

【问题讨论】:

  • open 导致关联的应用程序开始运行并加载文件,因此ctrl-F + 字符串必须以看起来像按键的方式发送到该应用程序。 Is there a sendKey for Mac in Python? 可能会有所帮助。
  • 这是否可行取决于打开文件的应用程序是否采用命令行参数,指示匹配给定字符串的字符串应突出显示。

标签: python macos terminal


【解决方案1】:

您与open 走在正确的轨道上;要使用 +F (我假设您在标签上使用的是 OS X),您可以使用 AppleScript 告诉系统事件应用程序执行击键:

os.system("open " + filename)

# You may need to add a sleep() here if the application is not already open and therefore needs time to load
os.system("""osascript -e 'tell application "System Events" to keystroke "f" using {command down}'""")
os.system("""osascript -e 'tell application "System Events" to keystroke \"""" + search_term + "\"'")

【讨论】:

  • 我会在 Python 级别使用三引号字符串,以避免转义那些双引号。
  • @BlacklightShining 是的——我正在考虑这一点,同时试图找出哪些反斜杠在哪里,但我希望它简洁并避免在问题中创建不必要的变量。
  • 什么不必要的变量?我只是建议对这两个字符串文字使用三引号而不是双引号——例如,"""osascript -e 'tell application "System Events" to keystroke "f" using {command down}'"""
  • 我将如何在search term 内进行合乎逻辑的操作?例如,即使“猫”和“狗”没有并排出现,它也能匹配它们吗?
  • @user99889 否 - 这只会触发系统“查找”选项,因此受限于您在应用程序中可以照常使用 CMD+F 执行的操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 2010-12-26
相关资源
最近更新 更多