Calling Java jar class with parameter from Python

jasonveldicott at gmail.com jasonveldicott at gmail.com
Sat Jul 21 12:11:18 EDT 2012


On Saturday, July 21, 2012 6:57:48 AM UTC-7, Roy Smith wrote:
> In article <mailman.2380.1342873263.4697.python-list at python.org>,
>  Peter Otten <__peter__ at web.de> wrote:
> 
> > subprocess.Popen([
> >   "C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe",
> >   "-cp",
> >   "C:\\antlr\\antlr-3.4-complete.jar",
> >   "org.antlr.Tool",
> >   "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"],
> >    stdout=subprocess.PIPE).communicate()
> 
> You might also want to try raw strings.  This should be identical to 
> Peter's version, but easier to read:
> 
> subprocess.Popen([
>   r"C:\Program Files (x86)\Java\jdk1.7.0_05\bin\java.exe",
>   r"-cp",
>   r"C:\antlr\antlr-3.4-complete.jar",
>   r"org.antlr.Tool",
>   r"C:\Users\Jason\Documents\antlr\java grammar\Java.g"],
>    stdout=subprocess.PIPE).communicate()
> 
> although I would probably refactor it like:
> 
> args = [r"C:\Program Files (x86)\Java\jdk1.7.0_05\bin\java.exe",
>         r"-cp",
>         r"C:\antlr\antlr-3.4-complete.jar",
>         r"org.antlr.Tool",
>         r"C:\Users\Jason\Documents\antlr\java grammar\Java.g",
>        ]
> proc = subprocess.Popen(args, stdout=subprocess.PIPE)
> proc.communicate()

The r string notation at least saves having to double type a bunch of backslashes, although the appearance prepended to the string takes a little getting used to.

Visually the separate array to handle arguments is perhaps cleaner, having more resemblance to the original command.

Thanks for the tips.



More information about the Python-list mailing list