【问题标题】:Python & macOS: open new Terminal window from Python, passing command to be executedPython & macOS:从 Python 打开新的终端窗口,传递要执行的命令
【发布时间】:2018-07-02 15:50:26
【问题描述】:

我正在使用以下两行 Python 代码从 Python 脚本打开一个新的终端窗口,这工作正常:

import os
os.system('open -a Terminal .')

现在我想向新的终端窗口传递一个要执行的命令,例如

ls

我该怎么做?

【问题讨论】:

  • 在此处查看此主题:stackoverflow.com/questions/19308415/…
  • 您想让终端以bash -c "ls; exec bash" 之类的起点打开。我对 OS X 不熟悉,但在大多数 Linux 终端仿真器中,您可以将它传递给一个标志。
  • 实际上,推荐线程中解释的 OS X 解决方案都不起作用...
  • 我认为this one 至少是部分重复。

标签: python macos terminal


【解决方案1】:

试试这个

import appscript

appscript.app('Terminal').do_script('ls')  # or any other command you choose

【讨论】:

  • appscript 模块已多年未得到支持或更新。
  • 我无法再下载 appscript 模块。答案不应该再被接受,因为它会浪费人们的时间。取而代之的是使用仍然活跃且正在运行的 applescript 模块。 :)
  • applescript模块的用法类似:applescript.tell.app( 'Terminal', 'do script "' + cmd + '"', background=True )
  • 不过,不要对旧答案投反对票,因为我们无法保证任何事情的未来。只需创建一个新答案
【解决方案2】:

由于旧答案已贬值,

如果你还没有下载applescript,

pip3 install applescript

python 脚本

from applescript import tell

#set what command you want to run here
yourCommand = 'ls'

tell.app( 'Terminal', 'do script "' + yourCommand + '"') 

【讨论】:

    猜你喜欢
    • 2013-10-18
    • 2019-10-26
    • 2013-12-25
    • 2020-05-14
    • 2014-05-27
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    相关资源
    最近更新 更多