Rectangle 27 65

The best current techniques for distributing your Python files in a jar are detailed in this article on Jython's wiki: http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts

For your case, I think you would want to take the jython.jar file that you get when you install Jython and zip the Jython Lib directory into it, then zip your .py files in, and then add a __run__.py file with your startup logic (this file is treated specially by Jython and will be the file executed when you call the jar with "java -jar").

This process is definitely more complicated then in ought to be, and so we (the Jython developers) need to come up with a nice tool that will automate these tasks, but for now these are the best methods. Below I'm copying the recipe at the bottom of the above article (modified slightly to fit your problem description) to give you a sense of the solution.

$ cd $JYTHON_HOME
$ cp jython.jar jythonlib.jar
$ zip -r jythonlib.jar Lib
$ cd $MY_APP_DIRECTORY
$ cp $JYTHON_HOME/jythonlib.jar myapp.jar
$ zip myapp.jar Lib/showobjs.py
# Add path to additional jar file.
$ jar ufm myapp.jar othermanifest.mf
__run__.py
# Copy or rename your start-up script, removing the "__name__  == '__main__'" check.
$ cp mymainscript.py __run__.py
# Add your start-up script (__run__.py) to the jar.
$ zip myapp.jar __run__.py
# Add path to main jar to the CLASSPATH environment variable.
$ export CLASSPATH=/path/to/my/app/myapp.jar:$CLASSPATH

On MS Windows, that last line, setting the CLASSPATH environment variable, would look something like this:

set CLASSPATH=C:\path\to\my\app\myapp.jar;%CLASSPATH%

Or, again on MS Windows, use the Control Panel and the System properties to set the CLASSPATH environment variable.

$ java -jar myapp.jar mymainscript.py arg1 arg2

Or, if you have added your start-up script to the jar, use one of the following:

$ java org.python.util.jython -jar myapp.jar arg1 arg2
$ java -cp myapp.jar org.python.util.jython -jar myapp.jar arg1 arg2
$ java -jar myapp.jar -jar myapp.jar arg1 arg2

The double -jar is kind of annoying, so if you want to avoid that and get the more pleasing:

$ java -jar myapp.jar arg1

You'll have to do a bit more work until we get something like this into a future Jython [Update: JarRunner is part of Jython 2.5.1]. Here is some Java code that looks for the __run__.py automatically, and runs it. Note that this is my first try at this class. Let me know if it needs improvement!

package org.python.util;

import org.python.core.imp;
import org.python.core.PySystemState;

public class JarRunner {

    public static void run(String[] args) {
        final String runner = "__run__";
        String[] argv = new String[args.length + 1];
        argv[0] = runner;
        System.arraycopy(args, 0, argv, 1, args.length);
        PySystemState.initialize(PySystemState.getBaseProperties(), null, argv);
        imp.load(runner);
    }

    public static void main(String[] args) {
        run(args);
    }
}

I put this code into the org.python.util package, since that's where it would go if we decide to include it in a future Jython. To compile it, you'll need to put jython.jar (or your myapp.jar) into the classpath like:

$ javac -classpath myapp.jar org/python/util/JarRunner.java

Then you'll need to add JarRunner.class to your jar (the class file will need to be in org/python/util/JarRunner.class) calling jar on the "org" directory will get the whole path into your jar.

$ jar uf org

Add this to a file that you will use to update the manifest, a good name is manifest.txt:

Main-Class: org.python.util.JarRunner

Then update the jar's manifest:

$ jar ufm myapp.jar manifest.txt
$ java -jar myapp.jar

hey Frank, thanks for the insight, really.. one thing, I am getting an error at the command "zip myapp.jar Lib/showobjs.py".. what is it supposed to do?

apparently, the jython interpreter has to be invoked before my script can do anything.. which tells me that "java -jar MyScript.jar" to run my python script is not possible. Thank you so much Frank!

Okay, I was wrong -- you do need call your distributed jar twice, so you end up with: "java -jar myapp.jar -jar myapp.jar arg1". That's very unsatisfying, and doesn't seem like it would be too hard to fix. I'll put this on my todo list to check out for 2.5.1.

BTW, I'll be back here with some kind of solution. I think a custom Java class based off of org.python.util.jython and an altered manifest file will do the trick. It may be a day or two before I can find the time, but stay tuned :)

Distributing my Python scripts as JAR files with Jython? - Stack Overf...

python jython distribution executable-jar
Rectangle 27 182

However, Python* has an added issue: There's a Global Interpreter Lock that prevents two threads in the same process from running Python code at the same time. This means that if you have 8 cores, and change your code to use 8 threads, it won't be able to use 800% CPU and run 8x faster; it'll use the same 100% CPU and run at the same speed. (In reality, it'll run a little slower, because there's extra overhead from threading, even if you don't have any shared data, but ignore that for now.)

There are exceptions to this. If your code's heavy computation doesn't actually happen in Python, but in some library with custom C code that does proper GIL handling, like a numpy app, you will get the expected performance benefit from threading. The same is true if the heavy computation is done by some subprocess that you run and wait on.

More importantly, there are cases where this doesn't matter. For example, a network server spends most of its time reading packets off the network, and a GUI app spends most of its time waiting for user events. One reason to use threads in a network server or GUI app is to allow you to do long-running "background tasks" without stopping the main thread from continuing to service network packets or GUI events. And that works just fine with Python threads. (In technical terms, this means Python threads give you concurrency, even though they don't give you core-parallelism.)

But if you're writing a CPU-bound program in pure Python, using more threads is generally not helpful.

Using separate processes has no such problems with the GIL, because each process has its own separate GIL. Of course you still have all the same tradeoffs between threads and processes as in any other languagesit's more difficult and more expensive to share data between processes than between threads, it can be costly to run a huge number of processes or to create and destroy them frequently, etc. But the GIL weighs heavily on the balance toward processes, in a way that isn't true for, say, C or Java. So, you will find yourself using multiprocessing a lot more often in Python than you would in C or Java.

Meanwhile, Python's "batteries included" philosophy brings some good news: It's very easy to write code that can be switched back and forth between threads and processes with a one-liner change.

If you design your code in terms of self-contained "jobs" that don't share anything with other jobs (or the main program) except input and output, you can use the concurrent.futures library to write your code around a thread pool like this:

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
    executor.submit(job, argument)
    executor.map(some_function, collection_of_independent_things)
    # ...

You can even get the results of those jobs and pass them on to further jobs, wait for things in order of execution or in order of completion, etc.; read the section on Future objects for details.

Now, if it turns out that your program is constantly using 100% CPU, and adding more threads just makes it slower, then you're running into the GIL problem, so you need to switch to processes. All you have to do is change that first line:

with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:

The only real caveat is that your jobs' arguments and return values have to be pickleable (and not take too much time or memory to pickle) to be usable cross-process. Usually this isn't a problem, but sometimes it is.

But what if your jobs can't be self-contained? If you can design your code in terms of jobs that pass messages from one to another, it's still pretty easy. You may have to use threading.Thread or multiprocessing.Process instead of relying on pools. And you will have to create queue.Queue or multiprocessing.Queue objects explicitly. (There are plenty of other optionspipes, sockets, files with flocks, but the point is, you have to do something manually if the automatic magic of an Executor is insufficient.)

But what if you can't even rely on message passing? What if you need two jobs to both mutate the same structure, and see each others' changes? In that case, you will need to do manual synchronization (locks, semaphores, conditions, etc.) and, if you want to use processes, explicit shared-memory objects to boot. This is when multithreading (or multiprocessing) gets difficult. If you can avoid it, great; if you can't, you will need to read more than someone can put into an SO answer.

From a comment, you wanted to know what's different between threads and processes in Python. Really, if you read Giulio Franco's answer and mine and all of our links, that should cover everythingbut a summary would definitely be useful, so here goes:

  • As a consequence of (1), sending data between processes generally requires pickling and unpickling it.**
  • As another consequence of (1), directly sharing data between processes generally requires putting it into low-level formats like Value, Array, and ctypes types.
  • Processes are not subject to the GIL.
  • There are some extra restrictions on processes, some of which are different on different platforms. See Programming guidelines for details.
  • The threading module doesn't have some of the features of the multiprocessing module. (You can use multiprocessing.dummy to get most of the missing API on top of threads, or you can use higher-level modules like concurrent.futures and not worry about it.)

thanks, but I am not sure I understood everything. Anyway I am trying to do it a bit for learning purposes, and a bit because with a naive use of thread I halved the speed of my code (starting more than 1000 threads at the same time, each calling an external app.. this saturates the cpu, yet there is a x2 increase in speed). I think managing the thread smartly might really improve the speed of my code..

@LucaCerone: Ah, if your code spends most of its time waiting on external programs, then yes, it will benefit from threading. Good point. Let me edit the answer to explain that.

@LucaCerone: Meanwhile, what parts do you not understand? Without knowing the level of knowledge you're starting with, it's hard to write a good answer but with some feedback, maybe we can come up with something that's helpful to you and to future readers as well.

@LucaCerone You should read the PEP for multiprocessing here. It gives timings and examples of threads vs multiprocessing.

@abarnert I have never studied nor implemented multi-threading multi-processing code.. and for Python I am experienced, but there is much room for improvement :) I tried to use the multiprocessing.Pool, and the Pool.map method, but I run into the non-picklable issue.. (the fun I want to apply to a list is a bound method.. I have tried several variations, read several discussions here on SO but couldn't entirely understand how to make it work)

multithreading - Python: what are the differences between the threadin...

python multithreading parallel-processing multiprocessing
Rectangle 27 172

However, Python* has an added issue: There's a Global Interpreter Lock that prevents two threads in the same process from running Python code at the same time. This means that if you have 8 cores, and change your code to use 8 threads, it won't be able to use 800% CPU and run 8x faster; it'll use the same 100% CPU and run at the same speed. (In reality, it'll run a little slower, because there's extra overhead from threading, even if you don't have any shared data, but ignore that for now.)

There are exceptions to this. If your code's heavy computation doesn't actually happen in Python, but in some library with custom C code that does proper GIL handling, like a numpy app, you will get the expected performance benefit from threading. The same is true if the heavy computation is done by some subprocess that you run and wait on.

More importantly, there are cases where this doesn't matter. For example, a network server spends most of its time reading packets off the network, and a GUI app spends most of its time waiting for user events. One reason to use threads in a network server or GUI app is to allow you to do long-running "background tasks" without stopping the main thread from continuing to service network packets or GUI events. And that works just fine with Python threads. (In technical terms, this means Python threads give you concurrency, even though they don't give you core-parallelism.)

But if you're writing a CPU-bound program in pure Python, using more threads is generally not helpful.

Using separate processes has no such problems with the GIL, because each process has its own separate GIL. Of course you still have all the same tradeoffs between threads and processes as in any other languagesit's more difficult and more expensive to share data between processes than between threads, it can be costly to run a huge number of processes or to create and destroy them frequently, etc. But the GIL weighs heavily on the balance toward processes, in a way that isn't true for, say, C or Java. So, you will find yourself using multiprocessing a lot more often in Python than you would in C or Java.

Meanwhile, Python's "batteries included" philosophy brings some good news: It's very easy to write code that can be switched back and forth between threads and processes with a one-liner change.

If you design your code in terms of self-contained "jobs" that don't share anything with other jobs (or the main program) except input and output, you can use the concurrent.futures library to write your code around a thread pool like this:

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
    executor.submit(job, argument)
    executor.map(some_function, collection_of_independent_things)
    # ...

You can even get the results of those jobs and pass them on to further jobs, wait for things in order of execution or in order of completion, etc.; read the section on Future objects for details.

Now, if it turns out that your program is constantly using 100% CPU, and adding more threads just makes it slower, then you're running into the GIL problem, so you need to switch to processes. All you have to do is change that first line:

with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:

The only real caveat is that your jobs' arguments and return values have to be pickleable (and not take too much time or memory to pickle) to be usable cross-process. Usually this isn't a problem, but sometimes it is.

But what if your jobs can't be self-contained? If you can design your code in terms of jobs that pass messages from one to another, it's still pretty easy. You may have to use threading.Thread or multiprocessing.Process instead of relying on pools. And you will have to create queue.Queue or multiprocessing.Queue objects explicitly. (There are plenty of other optionspipes, sockets, files with flocks, but the point is, you have to do something manually if the automatic magic of an Executor is insufficient.)

But what if you can't even rely on message passing? What if you need two jobs to both mutate the same structure, and see each others' changes? In that case, you will need to do manual synchronization (locks, semaphores, conditions, etc.) and, if you want to use processes, explicit shared-memory objects to boot. This is when multithreading (or multiprocessing) gets difficult. If you can avoid it, great; if you can't, you will need to read more than someone can put into an SO answer.

From a comment, you wanted to know what's different between threads and processes in Python. Really, if you read Giulio Franco's answer and mine and all of our links, that should cover everythingbut a summary would definitely be useful, so here goes:

  • As a consequence of (1), sending data between processes generally requires pickling and unpickling it.**
  • As another consequence of (1), directly sharing data between processes generally requires putting it into low-level formats like Value, Array, and ctypes types.
  • Processes are not subject to the GIL.
  • There are some extra restrictions on processes, some of which are different on different platforms. See Programming guidelines for details.
  • The threading module doesn't have some of the features of the multiprocessing module. (You can use multiprocessing.dummy to get most of the missing API on top of threads, or you can use higher-level modules like concurrent.futures and not worry about it.)

thanks, but I am not sure I understood everything. Anyway I am trying to do it a bit for learning purposes, and a bit because with a naive use of thread I halved the speed of my code (starting more than 1000 threads at the same time, each calling an external app.. this saturates the cpu, yet there is a x2 increase in speed). I think managing the thread smartly might really improve the speed of my code..

@LucaCerone: Ah, if your code spends most of its time waiting on external programs, then yes, it will benefit from threading. Good point. Let me edit the answer to explain that.

@LucaCerone: Meanwhile, what parts do you not understand? Without knowing the level of knowledge you're starting with, it's hard to write a good answer but with some feedback, maybe we can come up with something that's helpful to you and to future readers as well.

@LucaCerone You should read the PEP for multiprocessing here. It gives timings and examples of threads vs multiprocessing.

@abarnert I have never studied nor implemented multi-threading multi-processing code.. and for Python I am experienced, but there is much room for improvement :) I tried to use the multiprocessing.Pool, and the Pool.map method, but I run into the non-picklable issue.. (the fun I want to apply to a list is a bound method.. I have tried several variations, read several discussions here on SO but couldn't entirely understand how to make it work)

multithreading - Python: what are the differences between the threadin...

python multithreading parallel-processing multiprocessing
Rectangle 27 5

I'm starting this as a wiki collected from the other answers and my experience. Feel free to edit and add stuff, but please try to stick to practical advice rather than a list of broken things. Here's an old list of differences from the Jython site.

Jython does not use reference counting, and so resources are released as they are garbage collected, which is much later then you'd see in the equivalent CPython program

open('file').read()
with open('file') as fp
  • The __ del __ method is invoked very late in Jython code, not immediately after the last reference to the object is deleted.

mysqldb is a c module, and therefore will not work in jython. Instead, you should use com.ziclix.python.sql.zxJDBC, which comes bundled with Jython.

Replace the following MySQLdb code:

connection = MySQLdb.connect(host, user, passwd, db, use_unicode=True, chatset='utf8')
url = "jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull" % (host, db)
connections = zxJDBC.connect(url, user, passwd, "com.mysql.jdbc.Driver")

You'll also need to replace all _mysql_exception with zxJDBC.

Finally, you'll need to replace the query placeholders from %s to ?.

  • You can't express illegal unicode characters in Jython. Trying something like unichr(0xd800) would cause an exception, and having a literal u'\ud800' in your code will just wreak havoc.
  • C modules are not available, of course. So no NumPy or SciPy.
  • os.spawn* functions are not implemented. Instead use subprocess.call.

The Jython project is still alive, but is not fast-moving. The dev mailing list has about 20 messages a month, and there seem to be only about 2 developers commiting code lately.

python - Migrating from CPython to Jython - Stack Overflow

python migration jython cpython
Rectangle 27 3

Yes, with Jython you've real multi-threading. Jython (JPython successor's) is an implementation of Python that runs in the JVM. One of the main differences between Jython and the original project is that the first doesn't have the GIL and implements a real multi-threading support based on the JVM's implementation.

I'd suggest you to take a look to this book and the OReilly's one.

java - jython multithreading - Stack Overflow

java python multithreading jython
Rectangle 27 2

On your terminal/command prompt navigate to the Python home directory of the version for which you need to install the module. Then navigate into the scripts folder and run the pip command. Like below

cd C:/python27/Scripts
pip install XLRD

You basically need to point to the pip script for which you need to run this command. If thats for the pip script inside the python27, you need to navigate there or do like below as well

C:/python27/Scripts/pip install XLRD

If you have both the python27 & jython home directory & script paths in your 'PATH' environment variables, the path that was declared first takes precedence. To rearrange precedence, you would have to rearrange the order of the path declaration.

It defaults to jython since you have the jython home directory & scripts directory in your 'PATH' environment variable.

I also have the same for python why doesnt it go there then?

You must have had the jython path coming before the python27 path. In that case, it takes precedence.

Pip "install" Installs in Jython instead of python - Stack Overflow

python python-2.7 pip jython
Rectangle 27 68

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModiles if they're not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

I've installed JYthon, or i assume i did, and I keep trying to run the code that you outlined but it highlighted as a mistake. Does the installion of Jython need to go to a specific folder, either in the python or java folders?

@Shahab Not really helpful if you don't say what error appears..

There aren't any error, i'm just having a hard time integrating Jython into Netbeans

If there's no error it would work, so that's obviously not the case ;) "Error" does not mean runtime error, could be a compile error as well.

My bad, it was a poor use of the word. I was trying to add the jython.jar to my project and netbeans. I figured it out though

Calling Python in Java? - Stack Overflow

java python jython
Rectangle 27 68

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

I've installed JYthon, or i assume i did, and I keep trying to run the code that you outlined but it highlighted as a mistake. Does the installion of Jython need to go to a specific folder, either in the python or java folders?

@Shahab Not really helpful if you don't say what error appears..

There aren't any error, i'm just having a hard time integrating Jython into Netbeans

If there's no error it would work, so that's obviously not the case ;) "Error" does not mean runtime error, could be a compile error as well.

My bad, it was a poor use of the word. I was trying to add the jython.jar to my project and netbeans. I figured it out though

Calling Python in Java? - Stack Overflow

java python jython
Rectangle 27 42

I created pyenv which is a fork of Ruby's rbenv and modified for Python. Like pythonz, pyenv also supports Stackless, PyPy, and Jython.

Up and running in no time, thanks!

Holy crap that was easy

egg - Is there a python equivalent of Ruby's 'rvm'? - Stack Overflow

python egg equivalent rvm
Rectangle 27 41

I created pyenv which is a fork of Ruby's rbenv and modified for Python. Like pythonz, pyenv also supports Stackless, PyPy, and Jython.

Up and running in no time, thanks!

Holy crap that was easy

egg - Is there a python equivalent of Ruby's 'rvm'? - Stack Overflow

python egg equivalent rvm
Rectangle 27 1

There are a number of differences. First, Jython programs cannot use CPython extension modules written in C. These modules usually have files with the extension .so, .pyd or .dll. If you want to use such a module, you should look for an equivalent written in pure Python or Java. Although it is technically feasible to support such extensions - IronPython does so - there are no plans to do so in Jython.

you can simply call python scripts (or bash or Perl scripts) from Java using Runtime or ProcessBuilder and pass output back to Java:

Calling Python in Java? - Stack Overflow

java python jython
Rectangle 27 1

There are a number of differences. First, Jython programs cannot use CPython extension modules written in C. These modules usually have files with the extension .so, .pyd or .dll. If you want to use such a module, you should look for an equivalent written in pure Python or Java. Although it is technically feasible to support such extensions - IronPython does so - there are no plans to do so in Jython.

you can simply call python scripts (or bash or Perl scripts) from Java using Runtime or ProcessBuilder and pass output back to Java:

Calling Python in Java? - Stack Overflow

java python jython
Rectangle 27 8

The answer depends on what implementation of python is being used. If you are using lets say CPython (The Standard implementation of python) or Jython (Targeted for integration with java programming language)it is first translated into bytecode, and depending on the implementation of python you are using this bycode is directed to the corresponding virtual machine for interpretation. PVM (Python Virtual Machine) for CPython and JVM (Java Virtual Machine) for Jython.

But lets say you are using PyPy which is another standard CPython implementation. It would use a Just-In-Time Compiler.

Is Python interpreted, or compiled, or both? - Stack Overflow

python interpreted-language
Rectangle 27 4

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

Calling Python in Java? - Stack Overflow

java python jython
Rectangle 27 4

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

Calling Python in Java? - Stack Overflow

java python jython
Rectangle 27 1

If you want to get crazy with Python syntax:

map(lambda x: x.rstrip('\n'), input_list)
[x.rstrip('\n') for x in input_list]

I'm not sure which one is faster, though. I just wanted to use a lambda.

You sir, are amazing. Thanks a bunch!

You could strip the line while it is being looped over like so: foo.readline().rstrip('\n') too.

python - Jython: How to remove '\n' from the end of a string being rea...

python jython dss
Rectangle 27 2

Recently, I worked on a project for a professor at my school with a group. Early on, it was decided that we would write the project in Python. We definitely should have used CPython. We wrote the program in Python and all of our unit tests eventually worked. Because most people already have Java installed on their computers, and not Python, we decided to just deploy it as a Jython jar. We therefore wrote the GUI with Swing, because that's included in Java's standard library.

The first time I ran the program with Jython, it crashed immediately. For one, csv.reader's ".fieldnames" always seemed to be None. Therefore I had to change several parts of our code to work around this.

A different section of my code crashed as well, which worked fine with CPython. Jython accused me of referencing a variable before it was assigned anything (which drove me nuts and really wasn't the case). This is one example: ActiveState's Code Recipe's external sort

Worse yet, the performance was awful. Basically this code combined several CSV files, one of which was about 2 GB. In CPython, it ran in 8.5 minutes. In Jython, it ran in 25 minutes.

These problems happened with 2.5.2rc2 (the latest at the time of writing this post).

python - Migrating from CPython to Jython - Stack Overflow

python migration jython cpython
Rectangle 27 2

The following code runs just fine on my Ubuntu box with Jython 2.7 and Java 1.6 (tested with Eclipse and from the terminal):

package myjythonproject;
import org.python.util.PythonInterpreter;

public class MyJythonProject {

    public static void main(String[] args) {
        try
        {
            PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
            PythonInterpreter interp = new PythonInterpreter();
            interp.execfile("/home/vicent/foo.py");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Just make sure to compile and execute with jython.jar in your classpath.

I've just installed NetBeans 7.2.1 (version for Java SE) on my Ubuntu box, created a new Java project, MyJythonProject, and added the code shown above to the MyJythonProject.java file. Then on the Properties dialog of the project I've selected Libraries in the left pane. In the right pane I've selected the Compile tab, clicked the Add JARF/folder button and selected my jython jar (/opt/jython2.7a2/jython.jar). The I've closed the Dialog and in the Run menu of the main window I've selected Clean and Build Project (MyJythonProject). After that I've run the project and it works like a charm. No Python/Jython plugin required, just tell to your project where the jython.jar is installed.

Also notice that Python3 is not supported by Jython so you have to use a Python2.x interpreter.

Is your IDE well configured? I don't use NetBeans but maybe this link can be of help.

the thing is I'm using Netbeans 7.2.1 and to add python plugin I must downgrade to 6.5 which cues me a lot of problem inside my code. Also I tried many ways to add python plugin into Netbeans 7.2. but they all end up with failure. I think there is simple way to configure the path to python library. Like now I downloaded python and refer to it by using Properties props = new Properties(); props.setProperty("python.path", "C:\\Python33"); PythonInterpreter.initialize(System.getProperties(), props,new String[] {""}); unfortunately still get the same error is it because my path syntax ?!

Please, see my update. If it doesn't help you then I'll give up :) Just one more think, AFAIK Python3 is not yet supported by Jython so you should use a Python2.x interpreter.

how to add module of python into java using jython jar - Stack Overflo...

java python netbeans python-2.7 jython
Rectangle 27 2

I experienced a similar issue in that I want to be able to create simple command line calls for my jython apps, not require that the user go through the jython installation process, and be able to have the jython scripts append library dependencies at runtime to sys.path so as to include core java code.

# append Java library elements to path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "lib", "poi-3.8-20120326.jar"))

When running the 'jython' launcher explicitly on the command line, on Unix systems, it just runs a big shell script to properly form a java command line call. This jython launcher seems to have a dependency on reaching back to a core install of jython, and by some way of magic allows the proper handling of .jar files being added to the sys.path at runtime from within my .py scripts. You can see what the call is and block execution by the following:

jython --print run_form.py
java -Xmx512m -Xss1024k -Dfile.encoding=UTF-8 -classpath /Applications/jython2.5.2/jython.jar: -Dpython.home=/Applications/jython2.5.2 -Dpython.executable=/Applications/jython2.5.2/bin/jython org.python.util.jython run_form.py

But it's still just firing up a JVM and running a class file. So my goal was to be able to make this java call to a standalone jython.jar present in my distribution's lib directory so users would not need to do any additional installation steps to start using my .py scripted utilities.

java -Xmx512m -Xss1024k -classpath ../../lib/jython.jar org.python.util.jython run_form.py

Trouble is that the behavior is enough different that I would get responses like this:

File "run_form.py", line 14, in <module>
    import xls_mgr
  File "/Users/test/Eclipse/workspace/test_code/py/test/xls_mgr.py", line 17, in <module>
    import org.apache.poi.hssf.extractor as xls_extractor
ImportError: No module named apache

Now you might say that I should just add the jar files to the -classpath, which in fact I tried, but I would get the same result.

The suggestion of bundling all of your .class files in a jython.jar did not sound appealing to me at all. It would be a mess and would bind the Java/Python hybrid application too tightly to the jython distribution. So that idea was not going to fly. Finally, after lots of searching, I ran across bug #1776 at jython.org, which has been listed as critical for a year and a half, but I don't see that the latest updates to jython incorporate a fix. Still, if you're having problems with having jython include your separate jar files, you should read this.

In there, you will find the temporary workaround for this. In my case, I took the Apache POI jar file and unjar'ed it into its own separate lib directory and then modified the sys.path entry to point to the directory instead of the jar:

sys.path.append('/Users/test/Eclipse/workspace/test_code/lib/poi_lib')

Now, when I run jython by way of java, referencing my local jython.jar, the utility runs just peachy. Now I can create simple scripts or batch files to make a seamless command line experience for my .py utilities, which the user can run without any additional installation steps.

This is a good post, thanks for sharing your experience and knowledge. I've also been working with jython and experiencing the same problems as you. (+1)

Distributing my Python scripts as JAR files with Jython? - Stack Overf...

python jython distribution executable-jar
Rectangle 27 154

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

Also, is None is a bit (~50%) faster than == None :)

@myusuf3 You don't really need a proof for that. is is, basically, integer comparison while == is not only resolving references but comparing values which may have mismatching types.

One on favour of "is". When a variable can be either None or something that has no meaningful comparison with None. For example, a variable can be a numpy.array or None (my particular case).

I would like to add to what @TimLudwinski is saying: first, if someone chose to override the equality operator to make None a special case, why would we want to tell them otherwise? Second, "There should be one-- and preferably only one --obvious way to do it." And the obvious way to check if something is equal to something is, well, the equality operator.

python - What is the difference between " is None " and " ==None " - S...

python jython