executing terminal commands in Applescript - applescript

I executed the terrminal commnand "system_profiler SPApplicationsDataType" in AppleScript for to obtain installed app in MAC, I need to parse the output, Pls explain how to achieve it either thru Apple script or Python.

In Python you can use subprocess -
http://docs.python.org/library/subprocess.html
Specifically, the check_output method: http://docs.python.org/library/subprocess.html#subprocess.check_output
So you would just use:
output = subprocess.check_output(["system_profiler", "SPApplicationsDataType"])
print output # or do something else with it
Your command will be broken into an array, one element for each of your arguments.
In Applescript you could do something like:
set textReturned to (do shell script "system_profiler SPApplicationsDataType")
tell application "TextEdit"
activate
make new document at the front
set the text of the front document to textReturned
end tell
This will run the command and dump the output to TextEdit.

Related

Send multiple lines of quoted text to IPython in Terminal Window

I want to send a selected group of lines to my current ipython window from a texteditor (It's TextMate in this case, but that's largely irrelevant.) The script uses a bash call so it can accept the variable and then an Applescript call to push the code to the window.
This current script works, but it can only send a single non-nested line at a time. Is there a way to fix this so I can send multiple non-nested lines of code at once?
#!/bin/bash
QUOTED_TEXT=${TM_SELECTED_TEXT//\"/\\\"}
echo "$QUOTED_TEXT"
osascript <<- APPLESCRIPT
tell application "Terminal"
set currentTab to (selected tab of (get first window))
set tabProcs to processes of currentTab
set theProc to (end of tabProcs)
if theProc is not "Python" then
set currentTab to (do script "ipython")
end if
do script "$QUOTED_TEXT \n" in currentTab
end tell
APPLESCRIPT
I don't use either TM or ipython myself so can't provide an immediate answer to your exact problem, but here's some general thoughts on calling AppleScript from Terminal:
Never pass arguments to AS like that: it's a mis-quoting accident just waiting to happen. Wrap your AS code in an on run argv ... end run handler, then append your extra arguments to the osascript command when calling it in bash. osascript will then pass those arguments directly to AppleScript as a list of strings assigned to the argv variable. Safe and simple.
Rather than wrap your AS code in a bash script, just add #!/usr/bin/osascript at the top of your AS code, save it as a plain text file in an appropriate location (e.g. somewhere on your shell's $PATH, such as /usr/local/bin), then do chmod +x /path/to/script to make it executable. This will allow you to run it directly from Terminal.
If you want to access STDIN or environment variables directly within an AppleScript-based shell script, use the AppleScript-ObjC bridge to call NSFileHandle's fileHandleWithStandardInput()'s readDataToEndOfFile() and NSProcessInfo's processInfo()'s environment() respectively. To access ARGV, use an explicit run handler as described above.
By default, osascript automatically writes the value returned by the run handler to STDOUT; alternatively, you can write directly to STDOUT at any time via NSFileHandler (you can put a plain return statement at the end of run handler to ensure it returns nothing else). And osascript automatically writes the results of log commands to STDERR, and sets the return code to non-zero when your script throws an uncaught exception (e.g. use an error ERROR_STRING number ERROR_NUMBER statement to raise an exception directly in your AS code).
(BTW, I wrote a File library not long ago that includes a bunch of very nice handlers for writing AS-based shell scripts. I no longer develop or support it myself; however, various folks have already forked it, so if you do much AS+shell work you may find it a helpful source of AS code to cut-and-paste or even to use as-is.)

How to send a command using AppleScript to terminal one by one and save the output, which is not writable to file anywhere?

So, I have a problem. I have downloaded a program from the web. And it's a command line app. I have written a code, which generated some n-k commands to the app. I have written them into an output file. I can write an app in Python, but it freezes on some of the commands. I have tested them manually and seems like there are two issues:
Commands must be run one-by-one;
Some of the commands give an output like bla-bla-bla, this thing is not written into an output file. So, if I run a command ./app -p /file1 -o /file2 -s -a smth- > /fileOutput.txt The fileOutput.txt is empty, though in the terminal, there's is this bla-bla-bla message, stating, that something is wrong. If the command gives bla-bla-bla the app may freeze for a while.
Here is what I want to do:
CD into folder, the containing app;
For command in fileWithCommands perform command and start the next, only when the previous finishes;
If the command gives message, containing bla-bla-bla (cause it may look like file1 bla-bla-bla), write the command and this strange output into file badOutputs.txt.
Have never done applescript before. However, this's what I've done so far:
set theFile to "/Users/MeUser/Desktop/firstCommand"
set fileHandle to open for access theFile
set arrayCommand to paragraphs of (read fileHandle)
#I have found the previous code here: http://alvinalexander.com/mac-os-x/applescript-read-file-into-list-array-examples
close access fileHandle
tell application "Terminal"
activate
do script "cd /Users/MeUser/Desktop/anApp/"
repeat with command in arrayCommand
do script command
end repeat
end tell
Though there's a problem, if in one window the commands make up a huge queue. Without window 1 cd and the command are in different windows. And I am still unable to save the output.
UPDATE
Did with accordance to #Mark Setchell's recommendations. So now I have such code:
set theFile to "/Users/meUser/Desktop/firstCommand"
set fileHandle to open for access theFile
set arrayCommand to paragraphs of (read fileHandle)
close access fileHandle
repeat with command in arrayCommand
do shell script "cd /Users/meUser/Desktop/App/; " & command
end repeat
To the command I have added the following:
2>&1 /Users/meUser/Desktop/errorOut.txt
However, the apple script says that a mistake of the app is the mistake of the script. I.e.: file corrupted, app fails. I want it to write into error file where has it failed and move to the next command, while the script just fails.
Maybe not a complete solution, but more than a comment and easier to format this way...
First Issue
Your command-line app which writes on the Terminal may be writing to stderr rather than stdout. Try redirecting stderr to the same place as stdout by using
./app -p ... > /FileOutput.txt 2>&1
Second Issue
You cannot do:
do shell script cd somewhere
do shell script do_something
because each do shell script will execute in a separate, unrelated process. So your first process will start - in the default directory like all processes - and correctly change directory and then exit. Then your second process will start - in the default directory like all processes - and try to run your command. Rather than that, you can do this:
do shell script "cd somewhere; do_something"
which starts a single process which changes directory and then runs your command line program there.
Issue Three
Why do you want to send your commands to Terminal anyway? Does the user need to see something in Terminal - seems unlikely because you want to capture the output, don't you? Can't you just run your commands using do shell script?
Issue Four
If you want to keep your normal output separate from your error output, you can do:
./app ... params ... > OutputFile.txt 2> errors.txt
Suggestion 1
You can retain all the errors from all the scripts and accumulate them in a single file like this:
./app .. params .. >> results.txt 2>&1
That may enable you to deal with errors separately later.
Suggestion 2
You can capture the output of your shell script into an Applescript variable, say ScriptOutput, like this, then you can parse it:
set ScriptOutput to do shell script "..."
Suggestion 3
If errors caused by your script are stopping your loop, you can enclose them in a try block like this so they are handled and everything continues:
try
do shell script "..."
on error errMsg
display dialog "ERROR: " & errMsg
end try

Execute a shell command on a file selected in the Finder

I'm a very novice and infrequent applescript experimenter. I've tried for several hours now to learn the individual applescript commands for the following task, but I always run into errors. Perhaps someone much more adept at applescript will find this task easy and quick, and for that I would be very grateful. Here is the task:
I want to be able to manually select a document or file within the finder and then execute the following unix command on that file. I would then store the script under Finder's "Services" menu. The unix command is:
srm -rfv -m path/filename
In my attempts, I assumed that a script that would open Terminal and execute the command would be the way to go, but just couldn't get anything to work. Thank you in advance to any good programmers who can whip out such a script for me.
My tip: Create such services using Automator!
Create a new Service in Automator
Choose "File & Folder" as Input and "Finder"
Add "Run shell script"
Choose "as arguments" as input
Change echo "$f" to your command srm -rfv -m "$f"
Save it as "Safe delete"
From now on, if you select a file inside Finder you will find the option "Safe delete" in the context menu.
Enjoy, Michael / Hamburg
Craig's comment is pertinent, but I am just focus on the script itself, not on the shell command. the script bellow must be saved as Application and each time you drop 1 or more file on its icon, the shell script command will be executed for each file :
on open myFiles
repeat with aFile in myFiles -- repeat loop in case you drop more than 1 file on the icon script
try
do shell script "srm -rfv -m " & (quoted form of POSIX path of aFile)
end try
end repeat
end open
Still make sure that in your shell command 'srm -rfv', the 'v' is necessary because this script will not display any thing ! I don't think so. also I did not display error during remove. what do you want to do with error (like write protect, ...) ?
Update: I missed that the OP wants to create an OS X Service that integrates with Finder. ShooTerKo's answer shows how to do that (and his solution doesn't even require use of AppleScript).
The only potentially interesting thing about this answer is that it demonstrates AppleScript commands to open a file-selection dialog, get the chosen file's POSIX path and run a shell command with it, with some general background information about executing shell commands with do shell script.
Try the following:
# Let the user choose a file via an interactive dialog.
set fileChosen to choose file
# Get the file's POSIX path.
set filePath to POSIX path of fileChosen
# Use the path to synthesize a shell command and execute it.
do shell script "echo srm -rfv -m " & quoted form of filePath
Note:
There's no explicit error handling; if you don't want the script to just fail, you'll have to add error handling (try ... on error ... end try) to handle the case of the user canceling the file selection and the shell command failing (unlikely in this case).
The shell command has echo prepended to it in order to perform a dry run (see its output in Script Editor's Result pane); remove it to perform the actual deletion.
quoted form of is important for ensuring that a string value is included as-is in a shell command (no risk of expansion (interpretation) by the shell).
do shell script will NOT open a Terminal window - it will simply run the shell command hidden and return its stdout output, which is usually what you want. If the shell command signals failure via a non-zero exit code, an error is raised.

OSX script to open a new iTerm window and run a command based on a variable

I am trying to use the iTerm example shown here in answer to another query.
Basically I have a list of about 20 text files representing reports from different servers. I want to read each file name in the directory they live in and from that build a shell command that exists in a commands directory, then open a new iTerm window and then execute that shell script that I built.
I don't want to run them all in one window one after the other, I want them each to execute in their own window to speed up the processing.
Here is what I have, I can build the shell script name and store in foo quite happily and it seems I can open the new iTerm window OK too, but it is getting it to accept $foo as the command to be run I am having trouble with.
#!/bin/sh
FILES=/Volumes/reporter/uplod/lists/*
# eg each filename is of the type <path>/X07QXL29.txt
for f in $FILES
do
foo="del"
foo+=${f:32:1}
foo+=${f:36:2}
foo+=".sh"
# foo is now for example del729.sh using the above comment as the filename
# foo is the command I will want to run in its own new window
osascript <<END
tell application "iTerm"
tell the first terminal
tell myterm
launch session "Default Session"
tell the last session
write text "$foo"
write text "\n"
end tell
end tell
end tell
END
done
The error I am getting is:deltrash.sh: line 22: syntax error: unexpected end of file
Can anyone please give me a pointer?
Looking at iTerm applescript examples, something like that should work. Basically you have to set myterm variable to new terminal instance. Also be sure to put END marker at the beginning of line. It is not detected in your script, hence unexpected end of file error.
#!/bin/sh
FILES=/Volumes/reporter/uplod/lists/*
# eg each filename is of the type <path>/X07QXL29.txt
for f in $FILES
do
foo="del"
foo+=${f:32:1}
foo+=${f:36:2}
foo+=".sh"
# foo is now for example del729.sh using the above comment as the filename
# foo is the command I will want to run in its own new window
osascript <<END
tell application "iTerm"
set myterm to (make new terminal)
tell myterm
launch session "Default Session"
tell the last session
write text "$foo"
write text "\n"
end tell
end tell
end tell
END
done

Applescript conversion to Bash

I would like to make sure that an applescript can be converted to bash. Are there any ideas on how to do this? And if so, I'll place a simple applescript below to give you an example of how the script runs. In more clarity, I simply want a bash script or shell script to do what my applescript is doing. I want it to "enable" or change the default of the switch in system preferences, under "energy saver" that reads ...'start up automatically after a power failure'...:
set uiScript to "click checkbox \"Start up automatically after a power failure\" of list 2 of group 1 of window \"Energy Saver\" of application process \"System Preferences\""
run script "tell application \"System Events\"
" & uiScript & "
end tell"
any ideas on how to convert this script?
Thanks,
-Unimachead
You may not actually need to convert it - you can run AppleScript from within a bash script, using osascript.
$ man osascript
Note that you can run AppleScript either from a file or just include the source on the command line.

Resources