Sajeetharan
Sajeetharan

Reputation: 222710

How to pass a dictionary when calling a java program as subprocess in python?

I am trying to call a java jar program using python which works fine when i pass the input arguments as string, Now i need to pass dictionary as a input argument.

Here is the code:

Python:

class ExecuteKTR():
     def GET(self,r):
      web.header('Access-Control-Allow-Origin','*')
      web.header('Access-Control-Allow-Credentials', 'true')
      secToken = web.input().SecurityToken
      Domain = web.input().Domain
      fieldnames = ast.literal_eval(web.input().fieldnames)
      authResult = Auth.GetSession(secToken,Domain)
      if authResult.reason == "OK":
        args = ['ktrjob.jar', 'arg1', 'arg2', 'argN'] # Any number of args to be passed to the jar file
        result = jarWrapper(*args)
        print result
      elif authResult.reason == 'Unauthorized':
         result = comm.format_response(False,authResult.reason,"Check the custom message",exception=None)
         return result

def jarWrapper(*args):
    process = Popen(['java', '-jar']+list(args), stdout=PIPE, stderr=PIPE)
    ret = []
    while process.poll() is None:
        line = process.stdout.readline()
        print line
        if line != '' and line.endswith('\n'):
            ret.append(line[:-1])
    stdout, stderr = process.communicate()
    ret += stdout.split('\n')
    if stderr != '':
        ret += stderr.split('\n')
    ret.remove('')
    return ret

Java:

   String file = "";         
        if(args.length != 0)
        {
            file = args[0];
            for ( int i=0;i<=args.length;i++)
            {                   
                System.out.print(args[i]);
            }
        }

I need to pass a dictionary as a parameter to the java application. Sample one is,

{DateTime:12/03/2016,DealerName:'Test'}

Upvotes: 1

Views: 1606

Answers (3)

Simulant
Simulant

Reputation: 20150

Java only allows an Array of Strings as input parameter for a program, as the signature of the main method in Java shows:

public class MainClass {

    public static void main(final String[] args)
    {
        //do stuff
    }
}

You need to translate your dictionary in to one (or multiple) strings for the input for your java program and decode the transfered string inside your Java program. One solution would be to write your dictionary as a JSON String and parse a JSON Object from the provided String inside your Java program.

To create the JSON String in python you can use

strJSON = json.dumps(myDict)

In Java there are several libraries to import from Json format, have a look here.

Upvotes: 3

Serge Ballesta
Serge Ballesta

Reputation: 149185

Pass a dictionary to a program is rather meaningless: all you can pass to a subprocess are strings.

So you will have to choose a convention. If you need to be able to pass arbitrary objects, JSON is an option since libraries exist in both languages. If the dictionary is very simple and has always same structure, you could also pass only the variable parts. But beware, JSON do not specify any date format, so you will have to choose your own, and be consistent between Python and Java side.

Upvotes: 0

Radu Ionescu
Radu Ionescu

Reputation: 3532

You can use JSON to pass the dictionary as a String since in Python dictionary and JSON are basically the same

Upvotes: 1

Related Questions