Shell Script using Python

Hi,

Can someone show me a simple example where you don’t use a Python file. Something simple like adding 2 numbers or returning a simple list:

set the_list to (do shell script “Use a Python function here”)

I tried all kinds of stuff but couldn’t get a return without using a file in there. I wanted to get something returned like when you use the Python interactive thing.

Thanks,

Here:

my python_add(2, 3)
on python_add(a, b)
	return do shell script "python -c \"print '" & a & "+" & b & "=', " & a & "+" & b & "\""
end python_add

Essentially, you can place any python script into a quoted string and then have it executed with the “python -c” command:

set the_command to quoted form of "
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
     print i, a
"
return do shell script "python -c " & the_command

Jon

This works for me:

set the_list to do shell script “ls”
display dialog the_list

cheers!

dAVE

Hi,

Thanks for the replies.

Jonn, both of your examples was exactly what I was trying. I think I wasn’t using the print command in my tries. In the second script, I get this error:

" File “”, line 1

a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]
for i in range(len(a)):
print i, a[i]
^
SyntaxError: invalid syntax"

Maybe I need white spaces in front of the print?

Thanks a lot,

Yes, you do. For some reason it isn’t coming through in the script formatting for the BBS. If you are using 10.3, click the link to open the script in a new Script Editor Window and it will compile properly. Barring that, just add a single space before the word “print” and it should work fine.

This method allows you to access a whole new world of commands in your scripts. These commands don’t necessarily allow you do things that you can’t otherwise do, it just gives you the flexibility to use python if that’s what you’re comfortable with:

set the_command to quoted form of "
from datetime import date
now = date.today()
print now.strftime('Today is %m-%d-%y or %d %b %Y. It is a %A on the %d day of %B.')
"
set python_date to do shell script "python -c " & the_command
set shell_date to do shell script "date +'Today is %m-%d-%y or %d %b %Y. It is a %A on the %d day of %B.'"
return {python_date = shell_date, python_date}

Jon

Hi Jonn,

I added the white space and still get the error:

" File “”, line 1

a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]
for i in range(len(a)):
print i, a[i]
^
SyntaxError: invalid syntax"

Here’s the script:

set the_command to quoted form of "
a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]
for i in range(len(a)):
print i, a[i]
"
try
return do shell script "python -c " & the_command
on error err_mess
end try
err_mess

I’m using Jaguar so had to copy and paste the script. I also removed the spaces you get when copying from the script thing.

Maybe a Python command needs to come after the -c like in your first example?

BTW, I’m using the Python that came with Jaguar already installed.

Thanks,

Remove all extra spaces at the beginning and end of every line of the_command except before “print”:

set the_command to quoted form of "
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
 print i, a[i]
"
try
	return do shell script "python -c " & the_command
on error err_mess
	return err_mess
end try

If you still have problems, download this script:

http://homepage.mac.com/jonn8/as/dist/python_test.sit

Jon

Hi Jonn,

The downloaded script worked. I’m trying to find the difference but can’t see it. I’ll try to compare the text. All the spaces areomoved in the wrong places and I placed one before the print but it still didn’t work. I’ll post the difference if I find it.

Thanks a lot,

Hi Jonn,

This worked:

set nl to ASCII character 10
set the_command to quoted form of (nl & “a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]” & nl & “for i in range(len(a)):” & nl & " print i, a[i]" & nl)

return do shell script "python -c " & the_command

Don’t know if it’s a bug in Jaguar Script Editor or AppleScript’s ‘quoted form’.

After I dl your script, it ran ok. Eventually I made a small change in the script (put a return at the end and deleted it) and rechecked syntax. It didn’t work! So it was in compiling.

I typed in the above script by hand but first used returns instead of the newline character. It didn’t work. It works now. I just tried using backslash n within the string and now it works. I must remember:

repeat 100 times
“backslash n within strings”
end repeat

Now I get along with my learning Python and yes I can see the power in it.

Thanks again,

Note: I just tried using the n within the string, checked syntax and it worked. Then I made a small change to recheck syntax and I got the error as in my original post. So something is changing the newline character to carriage returns if you recheck the syntax. Guess I need to use the concatinating method in this system.

Have a good one,

As other folks have noted, Python relies on indentation to denote proper block structure (hint: use BBCode

...

tags when posting source to the board to preserve formatting), and lines must be newline (ASCII 10), not return, delimited.

BTW, application scripters interested in Python might like to check out my appscript module, which aims to provide MacPython with application scripting support even better than AppleScript’s own:

http://freespace.virgin.net/hamish.sanderson/

While it isn’t quite done yet it’s already very usable, and a finished version should be included in MacPython 2.4 when it ships later this year. There’s a number of sample scripts posted that should give you an idea of how it works, and the download includes more samples and [semi-complete] documentation, so folk already familiar with application scripting concepts shouldn’t have too much trouble figuring it out.

(Note: appscript requires OS 10.2+, MacPython 2.3+ and my HTMLTemplate module to use, and the gcc compiler, which is included with Apple’s Developer Tools, to install it. You can use my PyMod application for easy point-n-click installation.)

HTH

has

p.s. Here’s some more Python links that may be of help:

http://www.python.org/ – Python home
http://homepages.cwi.nl/~jack/macpython/index.html – MacPython home

The comp.lang.python newsgroup is a great place to go for help with Python in general; lots of very friendly folk who’ll be happy to assist. For assistance with MacPython-specific issues, you may want to subscribe to the MacPython SIG mailing list as well:

http://www.python.org/sigs/pythonmac-sig/

It’s more developer-oriented, but MacPython users are also welcome.

Hi has,

Thanks for the links. I’ve been through a couple of them several years ago I think but I stopped stopped learning Python. I didn’t like the ide with MacPython or the new ide in OSX (Terminal). I didn’t like running the py file either. Finally, Python needed to be installed in order to run a script. Now that I can run a Python script, at least I can cut out a few of those didn’t likes. Now I made a quick script tyemplate for running Python scripts:

set the_text to "

begin Python script

Fibonacci series:

the sum of two elements defines the next

a, b = 0, 1
while b < 10:
print b,
a, b = b, a+b

end Python script

"
set mod_text to ReplaceText(the_text, return, ASCII character 10)
set q to quoted form of mod_text
set python_return to (do shell script "python -c " & q)
– set as_value to (run script python_return) – for lists

on ReplaceText(the_text, s_string, r_string)
set new_text to “”
set def_tid to AppleScript’s text item delimiters
set AppleScript’s text item delimiters to {s_string}
try
set text_items to (every text item of the_text)
set AppleScript’s text item delimiters to {r_string}
set new_text to text_items as string
set AppleScript’s text item delimiters to def_tid
on error
set AppleScript’s text item delimiters to def_tid
beep 2
end try
return new_text
end ReplaceText

I’m starting with the tutorial again as you can see by the fib script. Currently, I’m thinking about how to get the different class types.

Using the Script Editor for this is good because I know how to use it as well as knowing AppleScript and being able to modify this “ide”.

Your statement about your app sounds interesting. I can’t understand how you can make an app to script apps with Python. Sounds interesting. do you plan to sell it in the future or will it be freeware?

Now, getting into calling functions and thinking about passing parameters programming wise. I like the name Python too. :slight_smile:

Thanks,

Yeah, the default MacPython IDE is pretty nasty; I never use it myself. The MacPython folk are working to replace it. There are plenty other platform-specific/cross-platform Python-only/multi-language IDEs available. e.g. PyOxide looks a promising if not-yet-mature OS X Python IDE. Or if you’ve already got BBEdit Pro, there’s a Python mode included with it. See http://www.python.org/cgi-bin/moinmoin/PythonEditors for a non-exhaustive list of editors to get you started.

OSA support is on the cards for MacPython, which’ll allow you to write and execute Python scripts on SE and SD. Can’t say when it’ll happen though; it’s not really my area.

appscript isn’t an application but a Python module. Completely open-source and free.

To answer how it works:

Any language that knows how to talk to the Apple Event Manager can send Apple events to Mac applications. There’s a common misconception that only AppleScript can have this ability: not so. It’s one of the Mac’s standard interfaces for interapplication communication, and is used for much more than just application scripting. e.g. Each time you double-click a document icon in the Finder, the Finder figures out what its creator application is and sends it an ‘oapp’ (open) event with a reference to the file.

Don’t ask me why other scripting languages haven’t had first-class application scripting support for years now; I’ve never managed to figure out the answer that question either. It’s an extremely odd omission, but I’ve been working to solve it for MacPython since switching last year. (Perl also has application scripting support in the form of Mac::Perl, but I’ve not used it myself so can’t really comment on it.)

Anyway, MacPython has had a low-level AEM bridge for years, but as it works with raw Apple events it’s not something most application scripters would want to use directly. It’s also had a high-level wrapper to this low-level API for some time, gensuitemodule, but it’s not very good or easy to use and isn’t very popular. So it’ll be getting replaced later this year with my appscript module, which is a much better design and feels very similar to application scripting in AppleScript (but with Pythonic syntax, of course). Meantime you can d/l and install appscript separately from my site.

HTH