6

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?

user3352382
  • 343
  • 2
  • 5
  • 12
  • See this thread here: https://stackoverflow.com/questions/19308415/execute-terminal-command-from-python-in-new-terminal-window – Daniel R. Livingston Jan 23 '18 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. – Norrius Jan 23 '18 at 18:39
  • Actually, none of the solutions for OS X explained in the recommended thread works... – user3352382 Jan 24 '18 at 07:59
  • I think [this one](https://stackoverflow.com/questions/989349/running-a-command-in-a-new-mac-os-x-terminal-window) is at least a partial duplicate. – Norrius Jan 27 '18 at 21:14

2 Answers2

4

Try this

import appscript

appscript.app('Terminal').do_script('ls')  # or any other command you choose
Ryan Loggerythm
  • 2,877
  • 3
  • 31
  • 39
  • appscript module hasn't been supported or updated in several years. – Keith Feb 21 '20 at 03:38
  • 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. :) – Keith Feb 29 '20 at 02:26
  • The usage of the applescript module is similar: applescript.tell.app( 'Terminal', 'do script "' + cmd + '"', background=True ) – Keith Feb 29 '20 at 02:28
  • 1
    Still, don't downvote old answers because we can't future-proof anything. Just create a new answer – Ryan Loggerythm Mar 02 '20 at 21:48
2

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 + '"') 
Shashwat Aryal
  • 126
  • 1
  • 11