Python & macOS: 从Python打开新的终端窗口并传递要执行的命令

7

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

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

现在,我希望给新的终端窗口传递一个要执行的命令,例如:

ls

我该怎么做呢?


请查看此线程:https://dev59.com/7WIk5IYBdhLWcg3waNZr - Daniel R. Livingston
1
你想让终端以类似 bash -c "ls; exec bash" 的起始点打开。我不熟悉 OS X,但在大多数 Linux 终端模拟器中,你可以通过标志传递它。 - Norrius
实际上,推荐的主题中针对OS X的解决方案都没有起作用... - user3352382
我认为这个至少是部分重复。 - Norrius
2个回答

4

试试这个

import appscript

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

AppScript模块已经好几年没有得到支持或更新。 - Keith
我无法再下载appscript模块了。这个答案不应该再被接受,因为它会浪费人们的时间。相反,使用仍然活跃的applescript模块吧。 :) - Keith
applescript模块的使用方式类似:applescript.tell.app('Terminal', 'do script "' + cmd + '"', background=True)。 - Keith
1
请不要因为我们无法未雨绸缪而对旧答案进行负面评价。如果需要更新,请创建一个新的答案。 - Ryan Loggerythm

3

由于旧答案已经过时,

如果您还没有下载,请下载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 + '"') 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接