Java and Python call each other

Source: Internet
Author: User
Tags python script

Java and Python call each other 

Python, as a scripting language, is used extensively for the writing of test cases and test code, especially for interactive business scenarios. In practical applications, many network management systems such as switches, firewalls and other equipment upgrades, often with the device interaction commands and device echo information are written in the Python script, the Java project directly invoke the corresponding Python script, perform the specific steps of the upgrade. However, the specific commands typically interact with the SSH connection established by the device, and finally Python is re-recalled to the Java-implemented SSH functionality.

Jython is a complete language, not a Java translator or just a Python compiler, which is a full implementation of the Python language in Java. Jython also has many module libraries that inherit from CPython. The most interesting thing is that Jython is not like CPython or any other high-level language, it provides all access to its implementation language. So Jython not only provides you with a Python library, but also provides all of the Java classes.

Java and Python call each other, you need to use Jython, you can download the Jython related jar package on the connection: Https://repo1.maven.org/maven2/org/python/jython.

Less nonsense, the simplest example is straightforward.

Jython Environment Class

[Java]View PlainCopy
  1. Package Com.webim.test.jython;
  2. Import Org.python.core.PySystemState;
  3. Import Org.python.util.PythonInterpreter;
  4. /**
  5. * Jython environment, Survival python interpreter
  6. * @author Webim
  7. *
  8. */
  9. Public Final class Jythonenvironment
  10. {
  11. private static jythonenvironment INSTANCE = new Jythonenvironment ();
  12. /** 
  13. * Private Construction method
  14. */
  15. private jythonenvironment ()
  16. {
  17. }
  18. /** 
  19. * Get a single case
  20. * @return Jythonenvironment
  21. */
  22. public static Jythonenvironment getinstance ()
  23. {
  24. return INSTANCE;
  25. }
  26. /** 
  27. * Get Python System status, specify Classloader/sys.stdin/sys.stdout and so on as needed
  28. * @return Pysystemstate
  29. */
  30. private Pysystemstate getpysystemstate ()
  31. {
  32. Pysystemstate.initialize ();
  33. final pysystemstate py = new Pysystemstate ();
  34. Py.setclassloader (GetClass (). getClassLoader ());
  35. return py;
  36. }
  37. /** 
  38. * Get Python Interpreter
  39. * @return Pythoninterpreter
  40. */
  41. Public pythoninterpreter Getpythoninterpreter ()
  42. {
  43. Pythoninterpreter inter = new Pythoninterpreter (null, getpysystemstate ());
  44. return Inter;
  45. }
  46. }

Java calls Python

[Java]View PlainCopy
  1. Package Com.webim.test.jython;
  2. Import Java.util.Map;
  3. Import Java.util.Map.Entry;
  4. Import Org.python.util.PythonInterpreter;
  5. This use of/*enum, can be used as a variant of the safety of the single case, it is worth learning oh ^_^ * *
  6. Public enum Execpython
  7. {
  8. INSTANCE;
  9. public void Execute (String scriptfile, map<string,string> properties)
  10. {
  11. //Get Python interpreter
  12. final Pythoninterpreter inter = Jythonenvironment.getinstance (). Getpythoninterpreter ();
  13. //Set Python properties, which can be used in Python scripts
  14. For (entry<string,string> entry:properties.entrySet ())
  15. {
  16. Inter.set (Entry.getkey (), Entry.getvalue ());
  17. }
  18. Try
  19. {
  20. //Python script is called through the Python interpreter
  21. Inter.execfile (ScriptFile);
  22. }
  23. catch (Exception e)
  24. {
  25. System.out.println ("Execpython Encounter Exception:" + E);
  26. }
  27. }
  28. }

Java classes for Python calls [Java]View PlainCopy
  1. Package Com.webim.test.jython;
  2. /**
  3. * Java classes for Python script calls
  4. * @author Webim
  5. *
  6. */
  7. Public class SayHello
  8. {
  9. private String UserName;
  10. Public String GetUserName ()
  11. {
  12. return userName;
  13. }
  14. public void Setusername (String userName)
  15. {
  16. this.username = userName;
  17. }
  18. public void say (int i)
  19. {
  20. System.out.println (i + ": Hello" + userName);
  21. }
  22. }
Test code

[Java]View PlainCopy
  1. Package Com.webim.test.jython;
  2. Import Java.util.HashMap;
  3. Import Java.util.Map;
  4. /**
  5. * Test the call flow of Java and Python
  6. * @author Webim
  7. *
  8. */
  9. Public enum Testexecpython
  10. {
  11. INSTANCE;
  12. public Void Test ()
  13. {
  14. String scriptfile = "test.py";
  15. map<string,string> properties = new hashmap<string,string> ();
  16. Properties.put ("UserName", "Demo");
  17. ExecPython.INSTANCE.execute (ScriptFile, properties);
  18. }
  19. }

Main Method Class

[Java]View PlainCopy
    1. Package com.webim.test.main;
    2. Import Com.webim.test.jython.TestExecPython;
    3. Public class Main
    4. {
    5. public static void Main (string[] args)
    6. {
    7. TestExecPython.INSTANCE.test ();
    8. }
    9. }
Python script
[Python]View PlainCopy
  1. #unicode =utf-8
  2. #################################################
  3. Importing Java Classes #通过java package
  4. From Com.webim.test.jython import SayHello
  5. execpy = SayHello ()
  6. #################################################
  7. #将python属性传入后续调用的java实例
  8. Execpy.setusername (UserName)
  9. Def say ():
  10. Execpy.say (5)
  11. return
  12. Say ()

Java and Python call each other

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.