To invoke a Python script in Java with dynamic arguments

Source: Internet
Author: User
Tags readline python script

Recently, I have come into contact with a wonderful interface, based on the boss constantly urging a rush of time, in the rewriting of the Java interface and the reuse of the existing Python script two paths to choose the latter, but in fact the latter is not much better, because I am a knowledge of Python is limited to the name of the spelling of the person, so, I will take my day from the configuration environment to the final successful invocation of the script process to organize, share to everyone.

First of all, I'll sort out my ideas in general (the following is a py instead of Python):
1. How does the py script work?
2. How do I invoke the py script in Java?
3. How to dynamically pass parameters to a PY script in Java.
4. Run the release

Next, I will follow the above three aspects of the idea to introduce separately, and show I have stepped on the pit.

How does a PY script work?
    1. The first step of course is to learn all the language is necessary: installation environment, here no longer repeat, give you a reference to my blog, very detailed. Installation of the Python environment under Windows
      Includes the installation environment to simple running statements and so on.
    2. In this case, I can already run a well-written PY program locally.
    3. Note: This is the first pit I stepped on, when configuring the Python environment, pay attention to the version of the Py script that you are currently running, Because the compatibility of 2.7 and 3.0 two versions is not very good, the environment configuration is not the same, may cause the written PY script syntax error, so be aware of this, select the appropriate version of the installation package.
Second, how to invoke the Py script in Java?
关于java中如何调用py脚本,网上一搜就有很多种方法,我主要实践了其中两种,当然最后采用的一种也是有原因的,下文会详细解释。

1. The first type, Jython
What is Jython?
He is actually a language, not a Java or Python interpreter. Use it to achieve, Java and Python code mutual access.
How do I use Jython?
How to use Jython
Required JAR Packages:
Why not use Jython in the end?
This is the second pit I have stepped on, the Jython tutorials quoted above, a few examples are very good to run, the function is very convenient to pass parameters, but in the running of the existing demo.py, but has been reported the following error:

After the query, found that the Java project is not the problem of the introduction of the package, but based on my understanding of the PY, I gave up this integrated approach, after all, need a little knowledge of the py. We'll have time to do the research later.

2. So after giving up Jython, I used the command line from Java to execute the PY runtime.getruntime (). exec (args), and then use the output stream to get the parameters.
In the case of the packaged py script, if you do not need to pass in parameters and only need to execute the PY file, then directly Baidu can get a lot of written code, I am here to provide a kind of I use this:

try {Process PR = Runtime. GetRuntime (). EXEC ("Python g:\\test.py"); BufferedReaderin = new BufferedReader (New InputStreamReader (pr.getinputstream ())) in .readline ())! = null) {line = Decodeunicode (line) ; System.out.println (line) in.close ()  Pr.waitfor () .out.println ( " End ") .printstacktrace ()  

Then see here, only need to modify Runtime.getruntime (). The parameters in exec ("") are changed to their corresponding file paths, which makes it easy to end this share, however, there are always, however, most of the time we call a reusable part, In order to pass in different parameters to get the corresponding results, please continue looking down.

Third, how to dynamically pass parameters to the py script in Java.
    1. First of all, first come together to define a concept, to the script dynamic parameter, I was very difficult to understand from the outset, how a Java parameter to the parameters of py? However, the script can be run directly from the command line, specifically what does it mean? I'm not sure, but I've found a way to be able to use and understand different ways of asking people. See also: Python getting command-line arguments
    2. Then a word does not fit the code:
      Java code:
try {//parameter to be passed String a = Getpara ("Car"). SUBSTRING (1), B ="D3455054", C ="lj12gks28d4418248", d ="Qingdao"; System. Out. println ("Start;;;" + a); Set command line incoming parameter string[] args = new string[] {"Python","/api_test.py", A, B, C, D}; Process PR = Runtime. GetRuntime (). EXEC (args); BufferedReaderin = new BufferedReader (New InputStreamReader (pr . getInputStream ())) ; String line, while (line = in . ReadLine ())! = null) {line = Decodeunicode (line); System.println (line);} in. Close (); PR. WaitFor (); System. Out. println ("End");} catch (Exception e) {E.printstacktrace ();}   

PY Code:

import sysprint "脚本名:", sys.argv[0]for i in range(1, len(sys.argv)): print "参数", i, sys.argv[i]

Operation Result:

Well, Jiangzi is done. All you have to do is pass in the parameters required in the Py script.

Run the publication

What can I say about running the release?
There is also a point to note, is the configuration of the server environment, Linux is generally integrated well, the other I am not very clear, but the most important point, when on-line debugging, be sure to pay attention to the path of the py file storage problem. Just the sauce.

Summarize

From the beginning of the complete touch of the brain, to now be able to invoke success, this less than a day of time, the pressure is very large, the face of unknown knowledge, the feeling I think everyone has experienced, but here, I would like to thank those who help my side friends ~ more exchanges, others may not have time to help you solve, But can provide the idea of the case, you can find the right direction earlier, such as "python command-line reference" This thing, I really do not know what Baidu search at the outset, the search for things may be with you need to completely not at the edge, then there is a direction is good. Of course, this direction is perfectly correct and lays the foundation for the success of the subsequent dynamic transfer of arguments, haha.
This blog only shows one of my features: I don't produce blogs, I just blog porters ~

Appendix: Legacy Issues

Project to obtain the Chinese parameters, has always been in the Py script to show the characters garbled, only the Chinese appearance of this situation, to the present there is no solution, then the use of a curve to save the way, but very bad, but there is no better solution, put here to continue to study later, Or you can have a good way and hope to have a lot of communication ~

Original address: 61417386

To invoke a Python script in Java with dynamic arguments

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.