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?

4
  • See this thread here: stackoverflow.com/questions/19308415/… Commented Jan 23, 2018 at 18:36
  • 1
    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. Commented Jan 23, 2018 at 18:39
  • Actually, none of the solutions for OS X explained in the recommended thread works... Commented Jan 24, 2018 at 7:59
  • I think this one is at least a partial duplicate. Commented Jan 27, 2018 at 21:14

3 Answers 3

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 + '"') 
Sign up to request clarification or add additional context in comments.

Comments

4

Try this

import appscript

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

4 Comments

appscript module hasn't been supported or updated in several years.
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. :)
The usage of the applescript module is similar: applescript.tell.app( 'Terminal', 'do script "' + cmd + '"', background=True )
Still, don't downvote old answers because we can't future-proof anything. Just create a new answer
1

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}" '"""
    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.