The macosxhints Forums

The macosxhints Forums (http://hintsforums.macworld.com/index.php)
-   Applications (http://hintsforums.macworld.com/forumdisplay.php?f=5)
-   -   AppleScript to display Safari's memory usage (http://hintsforums.macworld.com/showthread.php?t=64782)

hayne 12-15-2006 01:46 AM

Quote:

Originally Posted by NovaScotian (Post 342134)
The first step on Hayne's agenda was an unknown to me. I use BBEdit, but had never noticed that I had a choice of line endings - in AppleScript that's looked after for you.

I altered your processes slightly, but the result was:
ACB-G5:~/Desktop/Hayne bellac$ ./getProcessRss Safari
Looking for: "Safari"
PS: "Safari 42460
"
41.5 MB

Okay, so the stand-alone Perl script is now working fine for you.
In general, Unix utilities (e.g. Perl) will assume that all text files have the one-true-line-ending ('\n' or "Unix-style) and will silently fail if this is not the case. This is true of the script files (like this Perl script) and the data files they are processing. See the "line endings" section of this Unix FAQ for more info on this.

I suspect that the problem with the Perl script that is embedded within the AppleScript (in the subroutine 'getProcessMB') not working is due to the same sort of problem. I worried a bit about this when I wrote that AppleScript - I wasn't sure that the line-endings on that embedded Perl code were going to be correct. But I typed it into Script Editor and then wrote the embedded script to a file and it all checked out fine.

But I just read today on the AppleScript users mailing list that "Script Editor" and Satimage's "Smile" use different line endings - Smile uses the traditional Macintosh line endings. And I now realize that this might be relevant here.
I'm guessing that maybe NovaScotian used Smile to save the AppleScript and that is why it isn't working for him.

It's a bit nasty having to rely on the behaviour of one editor (Script Editor) to get the embedded line endings correct, but the only alternative I can see is to add in explicit newlines in the embedded Perl code and then string it all together into one unreadable mess of one line in the AppleScript.
I thought it was bad enough that I had to escape all the backslashes and quotes in that embedded Perl!

Bottom line: for the moment, NovaScotian, could you please try copy & pasting the above AppleScript into "Script Editor" instead (assuming that you were using "Smile" before).

hayne 12-15-2006 01:49 AM

Quote:

Originally Posted by mark hunte (Post 342150)
The Latest script runs fine, with Safari running or not.
My Safari seems to be running at around 25.X MB.
But the VersionA runs at 14.x MB.

You mean that the "VersionA" application is taking up 14 MB of RAM?
That's the sort of thing I was seeing last night. But now it is taking much less as I mentioned above - I don't understand why there would be this difference.

mark hunte 12-15-2006 01:54 AM

Quote:

Originally Posted by hayne (Post 342153)
You mean that the "VersionA" application is taking up 14 MB of RAM?
That's the sort of thing I was seeing last night. But now it is taking much less as I mentioned above - I don't understand why there would be this difference.

Thats Correct.

Will Run VersionB shortley

hayne 12-15-2006 01:56 AM

Quote:

Originally Posted by mark hunte (Post 342155)
Will Run VersionB shortley

You didn't read carefully enough - the two versions are called
VersionA (A for AppleScript)
and
VersionP (P for Perl)
:)

mark hunte 12-15-2006 02:26 AM

Doh.. :rolleyes: its late here.. or I should say early (gone 6 in the morning). Have not been bed yet.

I also find that when safari is playing up it uses lots of cpu, this sometimes happens after I have gone into another app just after safari, and at some point things get slow, a lot of beach balling. When I look for the reason why, A lot of the time its Safari in the background.

I do not know how helpful this is but I added cpu to the script.
It rough but seems to work. I put 50% cpu warning but I may lower it when I get a gauge on it.
Code:

on showAppSizeInTitle(appName, warnMB)
        if my appIsRunning(appName) then
                tell application appName
                        set cpu to ""
                        try
                                set cpu to word 2 of (do shell script "top -u -FR -l2 | grep -v 0.0% | grep % | grep -v Load |grep Safari| grep -v COMMAND | cut -c 7-24")
                        end try
                        if cpu is "" then
                                set cpu to "0.0"
                        end if
                        if (count of windows) > 0 then
                                set title to name of window 1
                                set delim to " *** "
                                set origTitle to my removeLastPart(title, delim)
                                set numMB to my getProcessMB(appName)
                                set title to origTitle & delim & numMB & " MB" & "*** " & cpu & "%"
                                set name of window 1 to title
                        end if
                       
                        if numMB is greater than warnMB then
                                display alert appName & " is taking more than " & warnMB & " MB"
                        end if
                        if cpu is greater than "49.0" then
                                display alert appName & " is taking more than " & "50 %cpu"
                        end if
                end tell
        end if
end showAppSizeInTitle

Maybe its worth adding a output file for the warnings.

Url,time, usage

NovaScotian 12-15-2006 11:04 AM

Neither of Hayne's versions work for me, though the perl script above by itself does.

I'm running this using a hot key rather than a idle script:

set tApp to "Safari" -- name of browser
set tLim to 75 -- acceptable memory use in MB
memToTitle(tApp, tLim) -- get title to include memory use
(* Script concept by Cameron Hayne, version by Adam Bell *)

to memToTitle(appName, tooHigh)
tell application "System Events" to if exists process appName then -- it's running
try
tell process appName to set N to name of window 1
set OK to true -- it's running and has a window open
on error
set OK to false -- no window
end try
else
set OK to false -- not running
end if
-- Running with window; get memory estimate to four significant figures
if OK then set MB to (100 * ((last word of (do shell script "/bin/ps -xc -o command,rss | grep " & appName)) / 1024) as integer) / 100
-- Put estimate in window title
tell application appName -- remove previous addition first
set dlim to " @ Mem = " -- something not likely to be found in a title
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to dlim
if (count N's text items) > 1 then set N to N's text item 1
set AppleScript's text item delimiters to tid
set name of window 1 to N & dlim & MB & " MB"
if MB > tooHigh then display alert appName & " is consuming more than " & tooHigh & " MB of memory"
end tell
end memToTitle

Note: Unlike Hayne's version, this one doe not trigger a warning if there are no windows. This works in Camino as well.

hayne 12-15-2006 01:49 PM

Quote:

Originally Posted by NovaScotian (Post 342206)
Neither of Hayne's versions work for me, though the perl script above by itself does.

Did you read my post #21 above where I explained my suspicion that the problem you are having with my AppleScript is also due to line-endings?

NovaScotian 12-15-2006 08:28 PM

I had not, Hayne, but just did (I've been out all day). I'm using Script Debugger 4 which may be part of the problem, because in Script Editor, the script with the command below succeeds every time I run it.

Problem solved, apparently. Excellent sleuthing, Hayne.

Code:

--on idle
showAppSizeInTitle("Safari", 150)
--return 10 -- updates every 10 seconds
--end idle

As an addendum, I've just written to LateNightSoftware that SD4 screws up timing comparisons too - for some sorts of script comparisons, the ratio of time taken by some handlers being compared can be off by a factor of 4 to 5 from those given in SE. Curiouser and curiouser.

NovaScotian 12-15-2006 09:09 PM

Last Minute Addition to previous post:

I copied the whole script from Script Editor to a new document in Script Debugger 4 and it works. - Obviously the line ending problem arises from copying from the web page, rather than having the script as an original.

I have found that it also works quite nicely in Camino, but getProcessMB fails when the app is Firefox, and Shiira doesn't know about its windows. It works beautifully in NetNewsWire (which does have a memory leak and grows very slowly if left running). I may modify it slightly to watch both.

Sorry to be so troublesome.

hayne 12-15-2006 09:59 PM

Quote:

Originally Posted by NovaScotian (Post 342315)
I'm using Script Debugger 4 which may be part of the problem, because in Script Editor, the script with the command below succeeds every time I run it.

Code:

--on idle
showAppSizeInTitle("Safari", 150)
--return 10 -- updates every 10 seconds
--end idle


So it would seem that my hypothesis (about the line-endings being an issue due to the use of different AppleScript editors) is verified.

This is an interesting issue for any embedded script (for use with 'do shell script') in AppleScript - a much more general issue than just the particular script under discussion in this thread. It is also an issue if some embedded text in an AppleScript were to be written to a file (using 'write' in AppleScript). See for example, the following AppleScript:
Code:

-- This AppleScript is intended for testing the behaviour of
-- embedded text strings with regard to end-of-line characters.
-- (See the "end-of-line characters" section of the following Unix FAQ:
--  http://forums.macosxhints.com/showthread.php?t=40648 )
--
-- On OS X, it is desirable that text files be saved with Unix-style
-- end-of-line characters.
-- The Unix 'file' command will report such a file to be:
-- "ASCII English text"
-- If, on the otherhand, the file is saved with traditional Mac line-endings,
-- it will be reported to be:
-- "ASCII English text, with CR line terminators"
--
-- Note that without the use of the subroutine 'fixLineEndings', this script
-- gives different results depending on which tool is used to compile it.
-- If the line that invokes 'fixLineEndings' is commented out,
-- using "Script Editor" (v 2.1.1) will give Unix line-endings
-- while Satimage's "Smile" (v 3.1.9) will give traditional Mac line-endings
--
-- Cameron Hayne (macdev@hayne.net)  December 2006

-- asks the user to specify a filename for saving
on chooseFileForSaving(defaultName)
        set savePrompt to "Save file as:"
        set filename to choose file name with prompt savePrompt default name defaultName
        return filename as string
end chooseFileForSaving

-- writes the string 'str' to 'filename'
on writeToFile(filename, str)
        set fRef to (open for access file filename with write permission)
        set eof fRef to 0
        write str to fRef
        close access fRef
end writeToFile

-- returns the result of running the Unix 'file' command on 'filename'
on unixFileCmd(filename)
        set unixFilename to POSIX path of filename
        set info to do shell script "/usr/bin/file " & unixFilename
        return info
end unixFileCmd

-- returns a string with Unix-style line endings
on fixLineEndings(str)
        set oldTIDs to AppleScript's text item delimiters
        set theLines to paragraphs of str
        set AppleScript's text item delimiters to ASCII character 10
        set fixedStr to theLines as string
        set AppleScript's text item delimiters to oldTIDs
        return fixedStr
end fixLineEndings

set theString to "Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe."

-- comment out the following line to test the behaviour of different tools
set theString to fixLineEndings(theString)

set filename to chooseFileForSaving("jabberwocky.txt")
writeToFile(filename, theString)
set fileInfo to unixFileCmd(filename)
display alert fileInfo

With the use of the 'fixLineEndings' subroutine, the above AppleScript reports that the file is "ASCII English text" (which is the desired result: Unix line-endings) whether I use "Script Editor" or Satimage's "Smile".

If I comment out the line that invokes the 'fixLineEndings' subroutine,
and then run the above AppleScript from "Script Editor", it still reports that the file is "ASCII English text".
But when I run the identical AppleScript (with the call to 'fixLineEndings' commented out) from "Smile", it reports that the file is "ASCII English text, with CR line terminators".

hayne 12-15-2006 10:12 PM

Quote:

Originally Posted by NovaScotian (Post 342321)
I copied the whole script from Script Editor to a new document in Script Debugger 4 and it works. - Obviously the line ending problem arises from copying from the web page, rather than having the script as an original.

That seems even weirder.

Quote:

getProcessMB fails when the app is Firefox
This is due to the fact that the Firefox executable is (for some strange reason known only to the Firefox developers) "firefox-bin" instead of "Firefox"
(The full path to the executable is /Applications/Firefox.app/Contents/MacOS/firefox-bin )

NovaScotian 12-16-2006 01:31 AM

Quote:

Originally Posted by hayne (Post 342339)
That seems even weirder.


This is due to the fact that the Firefox executable is (for some strange reason known only to the Firefox developers) "firefox-bin" instead of "Firefox"
(The full path to the executable is /Applications/Firefox.app/Contents/MacOS/firefox-bin )

Yes, I figured that out too. But even if I used that name, the perl script wasn't happy with it - it didn't error, it just didn't come back and I had to cancel.

I hope you'll report back to this thread if you figure out how to deal with script that have required line endings. One way (that I haven't tried yet) would be to replace all the \r with \n in a first line of the script and another would be do do that using text item delimiters and ASCII character 10. Finally, if the server of a site happens to be a Windows machine, then it can have CRLF as a paragraph delimiter, and that's often a problem with copied material. A generic way to fix this would be great, and I see that you've got "feelers" out for that. Please let us know if you find a "best" way.

hayne 12-16-2006 03:42 AM

Quote:

Originally Posted by NovaScotian (Post 342364)
I hope you'll report back to this thread if you figure out how to deal with script that have required line endings. One way (that I haven't tried yet) would be to replace all the \r with \n in a first line of the script and another would be do do that using text item delimiters and ASCII character 10. Finally, if the server of a site happens to be a Windows machine, then it can have CRLF as a paragraph delimiter, and that's often a problem with copied material. A generic way to fix this would be great, and I see that you've got "feelers" out for that. Please let us know if you find a "best" way.

I have modified the 'testEmbeddedStrings' AppleScript of post #30 to make use of a subroutine 'fixLineEndings' which takes a string and converts it to have Unix line endings.
With the use of this subroutine, that AppleScript gives the same result whether compiled in "Script Editor" or in "Smile".
If I comment out that subroutine, the same script gives different results when using "Script Editor" than when using "Smile".

I'd be very interested to hear what happens if you use "Script Debugger".

I think (but I haven't tested it) that the above 'fixLineEndings' subroutine might work to fix any string - even one with Windows-type line endings.

hayne 12-16-2006 03:51 AM

Quote:

Originally Posted by NovaScotian (Post 342364)
Yes, I figured that out too. But even if I used that name, the perl script wasn't happy with it - it didn't error, it just didn't come back and I had to cancel.

When I use the above stand-alone Perl script 'getProcessRss', it works fine if I use the process name "firefox-bin":
Code:

% getProcessRss firefox-bin
32.6 MB

But I can't see how to change the title of a Firefox window via AppleScript, so I gave up on making a version of the above AppleScript for Firefox.

mark hunte 12-16-2006 07:37 AM

Quote:

Originally Posted by hayne (Post 342381)
When I use the above stand-alone Perl script 'getProcessRss', it works fine if I use the process name "firefox-bin":
Code:

% getProcessRss firefox-bin
32.6 MB

But I can't see how to change the title of a Firefox window via AppleScript, so I gave up on making a version of the above AppleScript for Firefox.

The name is called «class pTit»
But even that does not work. The sdef for Firefox is very very basic. It does not even have the Apple Script basics. That could be why?

NovaScotian 12-16-2006 11:46 AM

Quote:

Originally Posted by hayne (Post 342338)
So it would seem that my hypothesis (about the line-endings being an issue due to the use of different AppleScript editors) is verified.

-- snip --

With the use of the 'fixLineEndings' subroutine, the above AppleScript reports that the file is "ASCII English text" (which is the desired result: Unix line-endings) whether I use "Script Editor" or Satimage's "Smile".

If I comment out the line that invokes the 'fixLineEndings' subroutine,
and then run the above AppleScript from "Script Editor", it still reports that the file is "ASCII English text".
But when I run the identical AppleScript (with the call to 'fixLineEndings' commented out) from "Smile", it reports that the file is "ASCII English text, with CR line terminators".

Script Debugger 4's results are the same as Smile's. Without fixLineEndings, the saved text returns CR line terminators, with the the handler active it's ASCII English text.

Good stuff, CH.

PS: your fixLineEndings is the simplest way to do it too.

NovaScotian 12-16-2006 12:19 PM

For the shell-script impaired, the test for line endings can be done in AppleScript too.

set txt to read alias ((path to desktop folder as text) & "SomeText.txt")
whichEnding(txt)

on whichEnding(T)
set NP to count paragraphs of T -- produces the same number for any ending
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to (ASCII character 13) & (ASCII character 10)
if (count text items of T) = NP then
set AppleScript's text item delimiters to tid
return "Windows"
end if
set AppleScript's text item delimiters to ASCII character 13
if (count text items of T) = NP then
set AppleScript's text item delimiters to tid
return "Mac"
end if
set AppleScript's text item delimiters to ASCII character 10
if (count text items of T) = NP then
set AppleScript's text item delimiters to tid
return "Unix"
end if
set AppleScript's text item delimiters to tid
end whichEnding

hayne 12-16-2006 12:52 PM

Quote:

Originally Posted by NovaScotian (Post 342433)
set txt to read alias ((path to desktop folder as text) & "jabberwocky.txt")
whichEnding(txt)

on whichEnding(T)
set NP to count paragraphs of T -- produces the same number for any ending
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ASCII character 10
if (count text items of T) = NP then return "Unix"
set AppleScript's text item delimiters to ASCII character 13
if (count text items of T) = NP then return "Mac"
set AppleScript's text item delimiters to (ASCII character 13) & (ASCII character 10)
if (count text items of T) = NP then return "Windows"
set AppleScript's text item delimiters to tid
end whichEnding

Doesn't the above suffer from the problem that "AppleScript's text item delimiters" is a global for the environment?
It seems to be returning before resetting "AppleScript's text item delimiters" to what it was. And hence the delimiter value will affect subsequent AppleScript in that script and all other until the environment is restarted (e.g.Script Editor is re-launched).

NovaScotian 12-16-2006 01:28 PM

Good catch, Hayne;

Several things wrong with it and that was only one of them. Order is important too. I've corrected the original rather than leave it stand broken.

hayne 12-16-2006 01:38 PM

Quote:

Originally Posted by NovaScotian (Post 342444)
Several things wrong with it and that was only one of them. Order is important too. I've corrected the original rather than leave it stand broken.

There still seems to be one (more subtle) problem with it. It is possible for a file to have mixed line-endings - this often happens if someone brings a text file over from Windows and then edits it a bit on OS X.
Your subroutine doesn't return anything in this case ('NP' would not match any of the "pure" cases).
This subject is tricky.


All times are GMT -5. The time now is 01:42 PM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.
Site design © IDG Consumer & SMB; individuals retain copyright of their postings
but consent to the possible use of their material in other areas of IDG Consumer & SMB.