Run java main class in command line/batch file/python script - python

I have a java class which is to be made into a tool so that I can give the input to the class as parameters and then produce the output in the command line, I have written the code in IntelliJ and want the code to be portable so that it can be used instantly by the click of a button. I have little experience in creating a bat file or python script.
package ase.ATool;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class AnaliT {
public static void main(String[] args) {
File file = null;
File dir = new File(args[0]);
File[] directoryListing = dir.listFiles();
StringBuffer componentString = new StringBuffer(100);
if (directoryListing != null) {
for (File child : directoryListing) {
float complexity = 0, noOfMethods = 0;
System.out.println(child.getPath() + " ");
String currentLine;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(child.getPath()));
System.out.println(bufferedReader);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I want to convert the above code in to a tool so i can invoke this main function from the command line, batch file or python file.

You could compile and run the java file from python by checking out the subprocess module:
https://docs.python.org/3/library/subprocess.html
You can also run java code using the system module: running a java file in python using os.system()
If you want to invoke Java code from python, take a look here:
Calling Java from Python
Here it is recommended you use Py4J.
Here you can find an example of running a Java Class from a .bat file: How to run java application by .bat file
As mentioned in a comment you can also compile the file with java using java target.java and then run it with java target in the same directory
I hope by showing you some of these resources you can guide yourself towards more specific help.

Related

Pass arguments to Python script to jar/Java [duplicate]

Is there a way to read data from the command prompt? I have a java program that relies on 4 input variables from an outside source. These variables are returned to the command prompt after I run a javascript program but i need a way to pass these variables from the command prompt into my java program, any help would be greatly appreciated!
While executing java program pass the parameters and all the parameters should be separated by space.
java programName parameter1 parameter2 parameter3 parameter4
This parameters would be available in your main method argument
public static void main(String[] args){
//This args array would be containing all four values, i.e. its length would be 4 and you easily iterate values.
for(int i=0; i<args.length; i++){
System.out.println("Argument " + i + " is " + args[i]);
}
Follow the link:
Command-Line Arguments - The Java™ Tutorials : https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
shared by #BackSlash.
It has all the content which would help you to clear all your doubts.
The content from the link is quoted below:
Displaying Command-Line Arguments passed by user from command-line to a Java program
The following example displays each of its command-line arguments on a
line by itself:
public class DisplayCommandLineParameters {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
To compile the program: From the Command Prompt, navigate to the directory containing your .java file, say C:\test, by typing the cd
command below.
C:\Users\username>cd c:\test
C:\test>
Assuming the file, say DisplayCommandLineParameters.java, is in the
current working directory, type the javac command below to compile it.
C:\test>javac DisplayCommandLineParameters.java
C:\test>
If everything went well, you should see no error messages.
To run the program: The following example shows how a user might run the class.
C:\test>java DisplayCommandLineParameters Hello Java World
Output:
Hello
Java
World
Note that the application displays each word — Hello, Java and World —
on a line by itself. This is because the space character separates
command-line arguments.
To have Hello, Java and World interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
C:\test>java DisplayCommandLineParameters "Hello Java World"
Output: Hello Java World

How to run C# Console Applications via Python?

I've created the following C# Console Application (.NET Core 3.1) with Visual Studio:
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//Check if args contains anything
if (args.Length > 0)
{
Console.WriteLine("args = " + args[0]);
} else
{
Console.WriteLine("args is empty");
}
//Prevent the application from closing itself without user input
string waiter = Console.ReadLine();
}
}
}
I am able to execute the application succesfully with one argument via cmd.exe:
CMD Input and Output
Now I'd like to run this program with one argument via Python. I've read How to execute a program or call a system command? and tried to implement it. However, it seems that the application is not being run properly.
The python code I am using via Jupyter notebook:
import subprocess
path = "C:/Users/duykh/source/repos/ConsoleApp2/ConsoleApp2/bin/Release/netcoreapp3.1/ConsoleApp2.exe"
subprocess.Popen(path) //#Also tried with .call and .run
//#subprocess.Popen([path, "argumentexample"]) doesn't work either
Output:
<subprocess.Popen at 0x2bcaeba49a0>
My question would be:
Why is it not being run (properly) and how do I properly run this application with one argument?
I've answered my own question. In a nutshell: I am pretty stupid.
Jupyter Notebook was running in the background and the application was being run there. That's why it didn't open a new prompt.
subprocess.Popen([path, "argument example"]) seems to work well for running a console application with an argument as input.

Get Current Working Directory With Python C Extension

I am building a Python C Extension that can load images.
To load a certain image, the user has to write the file path for that image.
The problem is that the user has to type the whole file path, even if the image is in the same directory as their module.
Python itself has some useful tools like os.path and pathlib that can help you to find the path of the current module.
I have searched the Python C API and I cannot seem to find any tools that relate to finding the current working directory in C.
What can I do - in C - to get the path to the directory of the user's module?
Are there any Python.h functions?
Am I taking the wrong approach?
The python c api can interact with lots of things you can do in Python.
How would you do this in Python? You would import os and call os.getcwd(), right?
Turns out you can do the same in the c api.
PyObject *os_module = PyImport_ImportModule("os");
if (os_module == NULL) { //error handling
return NULL;
}
PyObject* cwd = PyObject_CallMethod(os_module, "getcwd", NULL);
if (cwd == NULL) { //error handling
return NULL;
}
char* result = PyUnicode_AsUTF8(cwd);
And then when you're done with the module, or any pyobject in general, remember to call Py_DECREF() on it.

QProcess will not open python script

I cannot figure out why this does not work:
void Controller::on_buttonVisualTracking_clicked()
{
QProcess *trackingProcess = new QProcess();
trackingProcess->start("python C:\\visualTracking.py");
}
The specific script here is a pychart script, and if I simply run it from the command line, it executes correctly, opening up a window that displays the chart. That is something that I should emphasize, I'm expecting a new window to open displaying the pychart, which is what I get if I run the script myself.
I also tried this code to see if QProcess simply wasn't working. However this worked as expected and an empty notedpad window appeared.
void Controller::on_buttonVisualTracking_clicked()
{
QProcess *trackingProcess = new QProcess();
trackingProcess->start("notepad");
}
So then I thought maybe something is wrong with how I'm supplying arguments, so I tried this, which opened a notepad window with the visualTracking.py text as you would expect.
void Controller::on_buttonVisualTracking_clicked()
{
QProcess *trackingProcess = new QProcess();
trackingProcess->start("notepad C:\\visualTracking.py");
}
Thus, I'm completely at a loss. Why will QProcess not open up the python script?
UPDATE:
Per suggestions I've now tried these two options, neither one worked.
void Controller::on_buttonVisualTracking_clicked()
{
QString run = "C:\\Development\\Anaconda3\\python.exe";
QStringList args;
args << "C:\\visualTracking.py";
QProcess *trackingProcess = new QProcess();
trackingProcess->start(run, args);
}
and
void Controller::on_buttonVisualTracking_clicked()
{
QString commands = "python C:\\visualTracking.py";
QProcess *trackingProcess = new QProcess();
trackingProcess->start("cmd");
trackingProcess->write(commands.toLatin1().data());
if(!trackingProcess->waitForStarted()){};
}
UPDATE:
I thought I had a solution to this, but unfortunately I'm once again, on the development machine, unable to run python scripts again. I've no idea why the behavior changes randomly. My only guess is some windows security setting blocking my app from running a script, but I do not have any evidence to suggest this
With QProcess, you can only start real executables, not scripts. Therefore, you need to run the python interpreter python.exe and give your script as an argument.
See this answer for an example on how to do that. You might need to specify the full path to python.exe to get it to work for you, for example "C:\\Python26\\python.exe".
I see this problem.
But able to resolve by starting cmd first.
Also call ::waitForStarted to block until the process has started.
Check if it works for you (Details in comments).
//YOUR PY COMMAND
QString pyCommand("python C:\\visualTracking.py \n"); //try with out " \n" also...
//CREATE A PROCESS OBJECT
QProcess *qprocess = new QProcess(this);
//START THE CMD
qprocess->start("cmd");
//WRITE YOUR PY COMMAND TO PROCESS
qprocess->write(pyCommand.toLatin1().data());
//BLOCK THE PROCESS UNTILL IT STARTED
if (!qprocess->waitForStarted())
{
}
Are you using Qt5.8.0 MinGW version? I encountered the same issue and after switching to the Qt5.8.0 MSVC version everything worked just fine.
I haven't tried other version yet, but I think this may be the problem. Hope this help
UPDATE
I tried the QT 5.10.0 MinGW version, the bug still exist. However, using the gcc and g++ of manual installed MinGW won't have the same problem. I guess it's because the MinGW version shipped with the Qt is probably too old?
I've had a similar problem with an interactive script; the solution was to force it to run interactively:
auto *process = new QProcess{this};
connect(process, &QProcess::errorOccurred, []{
qFatal("process error occurred");
});
process->start("python", {"-i", "myscript.py"});

Running and obtaining results of a python program in C

The python script contains lots of libraries imported
My C code so far:
#include <stdio.h>
#include <python2.7/Python.h>
void main(int argc, char *argv[])
{
FILE* file;
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
file = fopen("analyze.py","r");
PyRun_SimpleFile(file, "analyze.py");
Py_Finalize();
return;
}
Is there any other way that I can use so that even if any modification in arguments or number of python scripts I call inside c program increases the same code can be used with little changes?
Can I use system call and use the result obtained from it?
One useful way is calling a python function within c, which is that you need instead of execute whole script.
As described in
>> here
You can do like this to call the python file from the C program:
char command[50] = "python full_path_name\\file_name.py";
system(command);
This piece of code worked for me...
I didn't use # include < python2.7/Python.h>
You can write the results from the python file to any text file and then use the results stored in the text file to do whatever you want to do...
You can also have a look at this post for further help:
Calling python script from C++ and using its output

Categories