Marriage: Java and Python

xiaoxiao2021-03-05  26

Marriage: Java and Python This article is recorded in the "Learning Python" book Chapter 10

JPython is a Python branch that recently appeared, and Mr. Jim Hugunin is completely written in Java. For Python and Java camps, JPython has quite exciting. Python users are quite happy that their existing Python knowledge can be applied to the Java development environment; Java users are also very happy they can use Python as a description Language (Scripting Language) to manipulate the Java system, test link library, and learn Java link libraries in translated environments.

You can get JPYTHON at http://www.jpython.org/, and its authorization is similar to CPYTHON (for JPython, which is different from JAVA version, CPYTHON).

JPYTHON is installed, contains: l JPython: JPython's direct translation environment. l JPYTHONC: It is used to compile JPython to Bytecode for Java. The procedure produced and the general Java class files are not different, which can be used to generate applet, servlet, beans, etc. l A set of program modules: Provide a standard Python link library to JPython users. l Some example programs: used to show the multi-style of JPython.

JPython's way of use and Python are very similar, please see the example below:

~ / book> JPYTHONJPYTHON 1.0.3 on java1.2beta4copyright 1997-1998 Corporation for National Research Initiatives >>> 2 35

In fact, JPython and CPYTHON have almost the same way. I want to know what truly differences in both, the latest information can be obtained from http://www.python.org/jpython/differences.html. The biggest difference in: l JPython is currently slower than CPYTHON. How slow? This will be different from the Java virtual machine and the JPython test program. However, JPython author has promised to do optimization in the future, making JPython speed as fast as CPYTHON, even faster. l JPython lacks some built-in modules or link library modules. For example, Os.System () cannot be used because this will cause Java and underlying OS interactions. There are some large extension modules (for example, tkinter) in JPython, because the Java environment does not have these tools (TK / TCL ratio).

Through JPYTHON, Python programmers can use Java link library JPython to let Python programmers seamlessly use Java link libraries, which is CPYTHON can't do. Please see the program jpythondemo.py and its execution results.

From Pawt Import SwingImport Java

DEF EXIT (E): java.lang.system.exit (0)

Frame = swing.jframe ('Swing Example', Visible = 1) Button = swing.jbutton (this is a swing button! ', actionperformed = exit) frame.contentpane.add (button) frame.pack () Transmit through this simple Procedure, you can see that writing a Python program with Java Swing when the GUI's Python program is quite simple. The first line first introduced (import) swing package (Pawt represents the location of the Swing module, can be in java.awt.swing, or com.sun.java.swing, or javax.swing). The second line introduces Java Package because Java.lang.System.exit () will be used in the session program. The fourth line establishes a JFrame object and sets the Visible property of this JFRAME component to "true". The fifth line establishes a JBUTTON object, set its log text, and specifies the function that the button must be executed is exit (). The last two lines put this JBUTTON object in the JFrame object, and then the size of the JFRAME is just right.

Experienced Java programmers may be a bit surprised to some parts of the JPythondemo.py program because they have some differences between the peer Java program. In order to let JPython use the Java link library as simple as in CPython, JPython has made a lot of things behind, and said that when JPython introduced (import) a Java Package, I will take the initiative to track the appropriate package, then pass through Java Reflection API finds the contents of the package, category, and method of Method. JPython also performs type conversion between Python and Java in real time. For example, in the jpythondemo.py program, the word "this is a swing" is a string of Python. Before the call jbutton's constructor, JPython will first find the correct constructor (through the parameters to judge), Then automatically transfer the Python string to the Java string. JPython does even use more intricular ways to allow you to use "ActionPerformed = EXIT" as a parameter in the JButton constructor. This method is that Java is not because Java does not allow function (or Method) as a parameter. In JPython, you don't have to build an ActionListener category like Java to provide ActionPerformed Method (of course, you can also use Java in JPython if you are not too 啰)).

JPython Asia Java Scripting Languagejpython is getting popular because it allows programmers to explore the continuous, formal Java link library. Everyone also found that JPython can help Python in Java as a description language (scripting language), let the end user build, test, or conduct other programming work. Further information on this area is more detailed in the Demo / Embed subntinder of JPYTHON software. A true JPYTHON / SWING example: grapher.pygrapher.py program (appearance is shown below) Allows the user to view graphics of mathematical functions with graphics. This program also uses the Swing GUI kit. Two text fields on the screen need to fill in the Python program. In the above field, the arbitrary Python program is filld, and the module required to introduce (Import) and define the related function. The second field (labeled "Expression:") is filled in the Python calculation (forced SIN (X)), rather than filling in Python's description. Each water bottle coordinate X value will be in this calculation during drawing.

The user can control the drawing of the drawing is a line chart or a solid map, or you can decide the drawing point, color. Moreover, you can also save the setting to the disk, and then call it again (through the Pickle module). Below is the program code for grapher.py:

From Pawt Import Swing, AWT, Colors, GridbagRight = swing.jlabel.rightApprove_option = swing.jfilechooser.Approve_OptionImport Java.ioImport Pickle, OS

Default_setup = "" "from math import * defsuarewave (x, order): total = 0.0 for i in Range (1, ORDER * 2 1, 2): Total = Total SIN (x * I / 10.0) / Float (i)) Return Total "" "

Default_expression = "Squarewave (x, ORDER = 3)" class chart (awt.canvas): color = colors.darkturquoisesStyle = 'Filled'

Def getPreferredSize (Self): Return AWT.DIMENSION (600, 300)

Def Paint (Self, Graphics): Clip = self.bounds graphics.color = colors.white graphics.FillRect (0, 0, Clip.width, Clip.height)

Width = int (clip.width * .8) Height = int (clip.Height * .8) x_offset = int (clip.width * .1) y_offset = clip.height - int (clip.Height * .1)

N = len (self.data); xs = [0] * n; ys = [0] * n

Xmin, xmax = 0, n-1 ymax = max (self.data) ymin = min (self.data) ZERO_Y = y_offset - int (-ymin / (ymax-ymin) * height) zero_x = x_offset int (-xmin / (xmax-xmin) * width)

For i in range (n): XS [i] = int (float (i) * width / n) x_offset ys [i] = y_offset - int ((Self.Data [i] -ymin) / (Ymax-Ymin) ) * Height) graphics.color = self.color if self.style == "line": graphics.drawpolyline (xs, ys, len (xs)) else: xs.insert (0, XS [0]); ys. INSERT (0, ZERO_Y) XS.Append (xs [-1]); Ys.Append (ZERO_Y) Graphics.FillPolygon (XS, YS, LEN (XS))

# Draw ax graphics.color = colors.black graphics.drawline (x_offset, zero_y, x_offset width, zero_y) graphics.drawline (ZERO_X, Y_OFFSET, ZERO_X, Y_OFFSET-HEIGHT)

# Draw labels leading = graphics.font.size graphics.drawString ( "%. 3f"% xmin, x_offset, zero_y leading) graphics.drawString ( "%. 3f"% xmax, x_offset width, zero_y leading) graphics. DrawString ("%. 3F"% ymin, zero_x-50, y_offset) graphics.drawstring ("%. 3F"% ymax, zero_x-50, y_offset-height leading)

Class GUI: DEF __INIT __ (Self): Self.NumeLements = 100 Self.Frame = swing.jframe (WindowClosing = Self.do_quit)

# Build Menu bar menubar = swing.jmenubar () file = swing.jmenu ("file") file.add (Swing.jMenuItem ("LOAD", ActionPerformed = Self.do_load) File.Add (Swing.jMenuItem ("SAVE ", actionperformed = self.do_save)) File.add (Swing.jMenuItem (" quit ", actionperformed = self.do_quit)) MenuBar.Add (file) self.frame.jmenubar = menubar # create widgets self.chart = char Visible = 1) Self.execent = swing.jtextarea (default_setup, 8, 60) Self.EVALENTRY = Swing.jtextField (default_expression, actionperformed = self.Update)

# create Options Panel OptionsPanel = swing.jpanel (AWT.FLOWLAYOUT (Alignment = AWT.FLOWLYOUT.LEFT))

# Whether the plot is a line graph or a filled graph self.filled = swing.JRadioButton ( "Filled", actionPerformed = self.set_filled) optionsPanel.add (self.filled) self.line = swing.JRadioButton ( "Line", ActionPerformed = Self.set_Line) OptionsPanel.add (Self.Line) styleGroup = swing.buttongroup () stylegroup.add (self.filled) stylegroup.add (self.line)

# Color Selection OptionsPanel.add (Swing.jlabel ("Color:", Right)) ColorList = Filter (Lambda x: x [0]! = '_', DIR (Colors)) Self.colorname = swing.jcomboBox (ColorList ) Self.colorname.ItemStateChanged = self.set_color optionSPanel.add (Self.colorname)

# Number of Points OptionsPanel.Add (Swing.jlabel ("Number of Points:", Right) Self.sizes = [50, 100, 200, 500] self.numpints = swing.jcomboBox (Self.sizes) Self.numpoints .selectedIndex = self.sizes.index (self.numelements) self.numpoints.itemStateChanged = self.set_numpoints optionsPanel.add (self.numpoints) # do the rest of the layout in a GridBag self.do_layout (optionsPanel) def do_layout (self , OptionsPanel: Bag = Gridbag (Self.Frame.ContentPane, Fill = 'Both', Weightx = 1.0, Weighty = 1.0) Bag.Add ("SETUP CODE:", Right)) Bag.Addrow (Swing .Jscrollpane (self.execentry), weighty = 10.0) Bag.add ("Expression:", Right) Bag.addrow (Self.Evalent, Weighty = 2.0) Bag.add ("Output : ", Right)) Bag.addrow (Self.Chart, Weighty = 20.0) Bag.jlabel (" Options: ", Right)) Bag.addrow (optionspanel, weighty = 2.0) Self.Update (none) Self .frame.visible = 1 self.frame.size = self.frame.getpreferredsize ()

Self.chooser = swing.jfilechooser () self.chooser.currentdirectory = java.io.file (os.getcwd ())

def do_save (self, event = None): self.chooser.rescanCurrentDirectory () returnVal = self.chooser.showSaveDialog (self.frame) if returnVal == APPROVE_OPTION: object = (self.execentry.text, self.evalentry.text, Self.chart.style, self.chart.color.rgb, self.colorname.selectedIndIndex, self.Numelements) File = Open (os.path.join (self.chooser.currentdirectory.path, self.chooser.selectedFile.name) , 'W') Pickle.dump (Object, File) file.close () Def do_load (self): self.chooser.rescancurrentdirectory () returnval = self.chooser.showopendialog (self.frame) if returnvalog (self.frame) if returnVal = = Approve_Option: File = Open (os.path.join (Self.chooser.currentDirectory.Path, Self.chooser.SelectedFile.Name)) (Setup, Each, Style, Color, ColorName, Self.NumeLements) = Pickle.Load File.close () self.chart.color = java.awt.Color (color) self.colorname.selectedIndex = colorname self.chart.style = style self.execentry.text = setup self.numpoints.selectedIndex = self.sizes.index (self.numelements ) Self.EValent.text = Each self.Update (NONE)

Def do_quit (self, event = none): import sys sys.exit (0) Def set_color: self.chart.color = getattr (colors, evenet.Item) self.chart.Repaint ()

Def set_numpoints (self): self.numelements = event.item self.Update (none)

DEF set_filled (self): self.chart.style = 'filled' self.chart.repaint () Def set_line (self): self.chart.style = 'line' self.chart.Repaint ()

Def update (self): context = {} Exec self.execent.text in context each = compile (self.evalent.text, ' ",' Eval ') NumBers = [0] * Self.NumeLements for x in xrange (self.NumeLements): context ['x'] = float (x) Numbers [x] = evAl (each, context) Self.Chart.Data = number == 'line': Self.Line.setSelected (1) else: self.filled.setselected (1) self.chart.repaint () GUI ()

The logic of this program is quite intuitive. With a good category name and Method name, you can easily understand the overview of the entire program. Most of this program can be written in Java (but a longer program code) is required. However, the part of the bold word can show the power brought by Python: At the top of this module, the default value of the setting field and the calculation field is defined, the former introduces the function of the mathematical module and defines a named SquareWave. Function; the latter calls this square wave function in a specific order parameter (as the parameter is getting bigger, the results graph will become more and more like square wave, echoing the name of this function). If you have already installed Java, Swing, and JPython, you may wish to try other settings and calculations.

In this example, use JPYTHON without Java's maximum niber to call the Python standard EXEC (), and then compiles the compiled computing field program with the program of setting fields. Call EVAL. The user can freely use Python on this two field.

JPython still has a considerable progress space, JIM Hugunin is continuously improved, optimized between Python and Java interface. JPYTHON is the second actual version of Python. JPython's appearance also forces Guido Van Rossum (Translator Note: He is the founder of Python) must clarify the difference between Python language and in. Fortunately, in this part, Jim and Guido seem to be consistent with each other.

Ayuan

9CBS certified blog expert

Blog expert

Huawei old employees

Big Data

More than ten years, in Huawei, Internet Corporation's experience, profound understanding and practical experience in CRM, big data, mainly sharing various project experience, including architecture, Java, big data and other articles

转载请注明原文地址:https://www.9cbs.com/read-33695.html

New Post(0)