Python & macOS: open new Terminal window from Python, passing command to be executed
Asked Answered
D

3

7

I am using the following two lines of Python code to open a new Terminal window from a Python script, and this works fine:

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

Now I would like to pass the new Terminal window a command to be executed, for example

ls

How can I do that?

Degeneration answered 23/1, 2018 at 18:14 Comment(4)
See this thread here: #19308915Independence
You want to make Terminal open with the starting point of something like bash -c "ls; exec bash". I'm not familiar with OS X, but in most Linux terminal emulators you can pass it in a flag.Kenwood
Actually, none of the solutions for OS X explained in the recommended thread works...Degeneration
I think this one is at least a partial duplicate.Kenwood
K
5

Since the old answer is depreciated,

Download applescript if you havent,

pip3 install applescript

python script

from applescript import tell

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

tell.app( 'Terminal', 'do script "' + yourCommand + '"') 
Kayo answered 31/3, 2020 at 10:9 Comment(0)
C
4

Try this

import appscript

appscript.app('Terminal').do_script('ls')  # or any other command you choose
Cheddar answered 7/1, 2019 at 5:28 Comment(4)
appscript module hasn't been supported or updated in several years.Infrasonic
I could no longer download the appscript module. The answer should no longer be accepted since it will waste peoples time. Instead use the applescript module which is still alive and kicking. :)Infrasonic
The usage of the applescript module is similar: applescript.tell.app( 'Terminal', 'do script "' + cmd + '"', background=True )Infrasonic
Still, don't downvote old answers because we can't future-proof anything. Just create a new answerCheddar
M
0

No need for extra libraries, see example below

import subprocess
import shlex

cmd = "sleep 10"

subprocess.run(
    shlex.split(
        f"""osascript -e 'tell app "Terminal" to activate' -e 'tell app "Terminal" to do script "{cmd}" '"""
    )
)
Maineetloire answered 3/10 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.