SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы

Назад

Scripting


Метки: python

One compelling benefit of using a dynamic language on the JVM is scripting. You can rapidly create and test code, and solve problems more quickly.

Here’s an example that shows a little of what you can do in a Jython script, and also gives you a sense of performance:

# Jython/Simple.py
import platform, glob, time
from subprocess import Popen, PIPE

print platform.uname() # What are we running on?
print glob.glob("*.py") # Find files with .py extensions
# Send a command to the OS and capture the results:
print Popen(["ping", "-c", "1", "www.mindview.net"],
               stdout=PIPE).communicate()[0]
# Time an operation:
start = time.time()
for n in xrange(1000000):
    for i in xrange(10):
            oct(i)
print time.time() - start

Note

The timeit module in the alpha distribution could not be used as it tries to turn off the Java garbage collector.

If you run this program under both cpython and Jython, you’ll see that the timed loop produces very similar results; Jython 2.5 is in beta so this is quite impressive and should get faster – there’s even talk that Jython could run faster than cpython, because of the optimization benefits of the JVM. The total runtime of the cpython version is faster because of its rapid startup time; the JVM always has a delay for startup.

Note that things that are very quick to write in Jython require much more code (and often research) in Java. Here’s an example that uses a Python list comprehension with the os.walk() function to visit all the directories in a directory tree, and find all the files with names that end in .java and contain the word PythonInterpreter:

# Jython/Walk_comprehension.py
import os

restFiles = [os.path.join(d[0], f) for d in os.walk(".")
             for f in d[2] if f.endswith(".java") and
             "PythonInterpreter" in open(os.path.join(d[0], f)).read()]

for r in restFiles:
    print(r)

You can certainly achieve this in Java. It will just take a lot longer.

Often more sophisticated programs begin as scripts, and then evolve. The fact that you can quickly try things out allows you to test concepts, and then create more refined code as needed.