How to run Python Script from Java Program - java

In my Java program I'm creating a Least Squares Approximation and exporting the coefficients, i.e. c1x+c2x^2+c3x^3..., to a text file that my Python script will read in and plot. However, I cannot even get a basic Hello World python file to run from my Java program. I've scoured the internet for answers and I've used all the tricks in the book. This is what I did: methodsOneThroughTwo methodsThreeThroughFour , and here is the output: exceptions .
I have the same python file, test.py, placed in two different locations, the first one being the directory of the java program (C:\Users\BScot\OneDrive\Desktop\Numerical Analysis\Lab2\test.py) and the second being in the directory of a python project, (C:\Users\BScot\OneDrive\Desktop\Numerical Analysis\Test\test.py), just to check if that would make a difference.
Some of the exceptions indicate that the file is found but it cannot run because it is not an executable; but when I add the python start command to the front of the file path it reads that it cannot find the file "python".
Any help would be much appreciated.

You have space character in python script path. Try to quote it with \" \"
Also you should take a look at ProcessBuilder: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

Related

How to recursively call a Java program with PowerShell and pass in a file path

I am trying to batch rename files in a folder. For example, right now I want to remove the character at the second index in the names of all of the files in a given folder. I have written a Java program that will do this given the path of the file.
The problem is that I am trying to batch the process with PowerShell, and I have very little knowledge of PowerShell. I basically just started using it today, and mainly to test run my Java program from the command line. I decided to try PowerShell for this because I saw a YouTube video where someone used PowerShell recursively to remove a certain character (like a "-") from every spot it appears in every file name in a folder. I thought maybe I could recurse with PowerShell to batch the process of changing every file name.
I want to recursively call the Java program with PowerShell and have PowerShell pass in each path of each file one by one in a folder to the Java program. I don't know if this is possible, but I'm hoping it is.
I have tried the following, though since I don't really any knowledge of PowerShell, I don't really know what to try. "Copy" is the name of the folder in which the files I want to modify are located.
get-childitem -recurse | java -cp "C:\Users\Media PC\Documents\Renamer\src\main\java" org.example.Main $_.name
I am getting the Java program to run, because I'm getting an error back from the program saying I didn't pass in a proper file path.
Building on Abraham Zinala's helpful comment:
Leaving aside the fact that invoking an external program (i.e., creation of a child process) file by file is inefficient:
Get-ChildItem -File -Recurse | ForEach-Object {
java -cp "C:\Users\Media PC\Documents\Renamer\src\main\java" org.example.Main $_.FullName
}
Note: The -File switch limits results to just files (doesn't include directories).
PowerShell's automatic $_ variable can only be used inside script blocks ({ ... }), so using $_.name as an argument as-is won't work.
See this answer for all contexts in which $_ is meaningfully defined.
In order to pass an argument to a command that isn't designed to take its input directly from the pipeline, use the ForEach-Object cmdlet for custom-processing of each input object one at a time.
Inside the script block passed to it, you can use $_ to refer to the pipeline input object at hand.
Get-ChildItem outputs instances of the following .NET types:
System.IO.DirectoryInfo(for directories) and
System.IO.FileInfo (for files)
Their .FullName property contains their full, file-system-native path, so $_.FullName is a robust way to refer to just that. Given that .Name only reports the mere file name, it wouldn't be sufficient to identify the file at hand in a recursive traversal of the current dir.
In PowerShell (Core) 7+, you could use just $_, because there such instances consistently stringify as the value of their .FullName property (when passing arguments to an external program, objects are implicitly stringified) - unfortunately, this is not the case in Windows PowerShell; see this answer.

How to use Java to run a command through Mac OS Terminal

I am a high school student working on a project that will convert the video from a YouTube link into an MP3 and download it. However, the way that the video form YouTube is downloaded and converted is through the Mac OS terminal by using YouTube-dl.
This is what I put into the terminal:
youtube-dl -f bestvideo+bestaudio \"ytsearch:{https://www.youtube.com/watch?v=5X-Mrc2l1d0}\"
This works in terminal, but when I try to use:
Runtime.getRuntime().exec("cd /Users/poppa/Desktop/IA Vids");
and there's an error saying "No such file or directory"
Another Problem that I am having is running the code that is inputted into the Terminal from Java. I'm using IntelliJ IDEA if that helps. Thank You!
You have a space in the directory path. Try putting double quotes around like this:
Runtime.getRuntime().exec("cd \"/Users/zeidakel/Desktop/IA Vids\"");
Also note that executing cd command from JVM may have no effect on current user dir when (for example) creating files with new File("path")
If cd means change directory (and isn't the name of an executable), then it almost certainly won't take effect, even if it is executed correctly. The process spawned by exec() will have a working directory, and it can be changed -- but that change will only affect the spawned process.
In addition, having spaces in arguments to exec() is inherently problematic. exec() is not a shell, and you won't be able to protect the string from being split at the spaces by using shell mechanisms like quotes. Instead, you need to split the command into arguments yourself, knowing where the splits should be, and then use the form of exec() that takes a String[] as input. That is, split the arguments into an array of strings yourself, rather than relying on exec() to do it for you (wrongly).
Runtime.exec() is fraught with difficulties, and needs very careful handling. I've written extensively about this subject here:
http://kevinboone.me/exec.html

Translating a Jar-opening Batch file into its MacOS Equivalent

Hello again Stack Overflow!
I am currently working on a Java program that is essentially a digitized character sheet for a Dungeons and Dragons style adventure. I'm currently learning how to use IntelliJ IDEA, and while I haven't been able to figure out how to create a standalone executable .jar file, I have been able to find a workaround in the form of a .bat file that I have nicknamed rubberglove.bat (because if you can't open a jar, you use a...).
However, as in my previous post, I've run into a problem, as one of my new players uses a Mac, and since I don't know if it's possible to run rubberglove.bat in a non-Windows environment, I'll probably have to translate it into something MacOS can understand. However, I've never owned a Mac, so I'm not sure what the file extension even is, let alone what to put inside.
The contents of rubberglove.bat are shown below:
java -jar [program_name].jar
What would the Mac equivalent of this file and the commands inside? Thanks in advance for all your help!
Create a file called rubberglove (or rubberglove.sh, the file suffix is optional). And then set the execute bit. Something like
$ cat << EOF > rubberglove
#!/usr/bin/env bash
java -jar [program_name].jar
EOF
$ chmod +x rubberglove
$ ./rubberglove
Error: Unable to access jarfile [program_name].jar
Adjust "[program_name]" as needed.

Imagemagick not working in windows + java

I am using imagemagick in my application. Our development machine is Windows and live server is linux. Now, in online it is working fine online. But not in development machine. I downloaded and installed Imagemagick latest release for Windows and when i try the below command in DOS-prompt, it is working fine.
convert -sample 100x100 D:\test.jpg D:\test-cropped.jpg
But when i run the same as command-line in Java program, it is not working and not giving any error too.
My code is :
Runtime.getRuntime().exec("convert -sample 250x150 "+pathName+digest+".jpg "+pathName+digest+"_thumb.jpg");
Any help is appareciated.
convert.exe is available in ImageMagick installation directory. So you need to add ImageMagick installation directory in environment variable path.
Another option is to provide complete path of convert.exe as :
Runtime.getRuntime().exec("C:\\program files\\ImageMagick\\convert -sample 250x150 "+pathName+digest+".jpg "+pathName+digest+"_thumb.jpg");
try
execute convert using the absolute path
quote your parameter input file and output file, in case they contain space
I suspect the problem is spaces in pathnames, but the solution is NOT to use escapes or quotes. The exec(String) method splits the string into "arguments" in a completely naive fashion by looking for white-space. It pays no attention whatsoever to quoting, etcetera. Instead, you will end up with command names and arguments that have quote characters, etcetera embedded in them.
The solution is to use the overload of exec that takes a String[], and do the argument splitting yourself; e.g.
Runtime.getRuntime().exec(new String[]{
"convert", // or "D:\\Program Files (x86)\\ImageMagick-6.8.0-Q16\\convert\\"
"-sample",
"250x150",
pathName + digest + ".jpg",
pathName + digest + "_thumb.jpg"
});
The other thing you could do is to capture and print any output that is written to the processes stdout and stderr.
In my case, the problem I was facing that from java compare command was working fine using Runtime.getRuntime().exec(), but when using convert, it was not working and returning me exit value as 4.
Compare execution returns exit value 0, telling that it is successfully executed.
I have system path updated with the ImageMagic's installation directory, still it was not picking 'convert' exe file. So, I started giving complete path of the convert.exe file instead of only writing only convert
e.g:
Runtime.getRuntime().exec("C:/Program files/ImageMagic......../convert.exe myImage1 -draw .... myImage2") and it worked fine this time.
Some how system was not able to pick the convert application and giving full path sorted it out. May be this solution would help someone facing same type of issue.

Runtime exec output path

I am trying to run a perl command with Java runtime exec in linux/ubuntu/gnome. The command generates an pdf file, but it saves it in my home folder. Is there any way that the exec method can set an output path for the commands executed? Thanks in advance.
The exec method just runs the command on the operating system, so you'll want to change the command you're running with exec more than anything in "Java" per se.
There are a few possibilities:
Change the working directory of your java program. The .pdf is being saved in your working directory because this is where the program is being run.
Unfortunately it's not simple to change this value after the program has been launched. It is, however, trivial to change before the program starts; just change the working directory before starting the program.
Move the file to it's desired location after it's been created in your home directory.
Change the command so that it includes the target location. Your perl script may have an option that will enable you to save it's output to a certain location (usually -o or --output). Using this your program would change from:
Runtime.exec("perl someprogram");
to something like:
Runtime.exec("perl someprogram -o /path/to/some.file")
You might be able to use "output redirection", if there is no option to do this.
Try something like what's below as your argument:
Runtime.exec("perl someprogram > /path/to/some.file")
Unfortunately, without knowing more details of your situation I can't provide more concrete advice.
While each approach has benefits and drawbacks, it's probably best to just implement the one that you understand best; if you can't get one to work, try another.
A good, free online resource for learning is Introduction to Linux: A Hands On Guide.
Section 2.2 has details on cd which you can use for 1..
Section 3.3, section 3 teaches about the mv command, which will be useful in 2..
Section 5.1 is about I/O redirection. Knowing about "output redirection" and the > operator, are important for 4..
For 3., you'll have to consult the documentation of the perl program you're using.
You could modify the Perl script to accept an absolute path for the output.
You can trying setting the working directory using exec(java.lang.String[], java.lang.String[], java.io.File) where File is the directory the command is executed from.
If all else fails, you'll can always copy the generated file from the Home directory to your final location.

Categories

Resources