I’ve seen similar questions (e.g. Running a command in a new Mac OS X Terminal window ) but I need to confirm this command and its expected behavior in a mac (which I don’t have). If anyone can run the following in Python 3 Mac:
import subprocess, os
def runcom(bashCommand):
sp = subprocess.Popen(['osascript'], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
sp.communicate('''tell application "Terminal"\nactivate\ndo script with command "{0} $EXIT"\nend tell'''.format(bashCommand))
runcom('''echo \\"This is a test\\n\\nThis should come two lines later; press any key\\";read throwaway''')
runcom('''echo \\"This is a test\\"\n\necho \\"This should come one line later; press any key\\";read throwaway''')
runcom('''echo \\"This is testing whether I can have you enter your sudo pw on separate terminal\\";sudo ls;\necho \\"You should see your current directory; press any key\\";read throwaway''')
Firstly, and most basically, is the “spawn new terminal and execute” command correct? (For reference, this version of the runcom function came from this answer below, and is much cleaner than my original.)
As for the actual tests: the first one tests that internal double escaped \\n characters really work. The second tests that we can put (unescaped) newlines into the “script” and still have it work just like semicolon. Finally, the last one tests whether you can call a sudo process in a separate terminal (my ultimate goal).
In all cases, the new terminal should disappear as soon as you “press any key”. Please also confirm this.
If one of these doesn’t work, a correction/diagnosis would be most appreciated. Also appreciated: is there a more pythonic way of spawning a terminal on Mac then executing a (sudo, extended) bash commands on it?
Thanks!
This is hard to answer, since those commands do what I expect them to do, which might not be what you expect them to do.
The
\\nwith the doubled backslash does indeed work correctly in that it causesechoto emit a newline character. However, no double quotes are emitted byecho.That works also.
There is no reason why this should not work also, and indeed it does.
That will not work because of several reasons:
readin bash will by default read a whole line, not just one characterOther problems:
osascriptwill appear in the terminal window before it is executed. in the examples above, the user will see every “This is a test […]” twice.$EXITis supposed to dolscommand will show the user “the current directory” only in the sense that the current working directory in a new terminal window will always be the user’s home directorythrowawaywill not be available after the scriptbashCommandexitsFinally, this script will not work at all under Python 3, because it crashes with a
TypeError:communicate()takes a byte string as argument, not a string.You should look into PyObjC! It’s not necessarily more pythonic, but at least you would eliminate some layers of indirection.