I have a python script that searches the given search term on youtube and prints out the result on the console. When I run this script on cmd.exe it takes 2 seconds for it to print out the result but it does. However, I cannot capture the command line output on my Java code. It returns an empty ArrayList. I am one hundred percent sure that I execute the same command in my code as cmd.exe. What should I do to get the output of this script in my Java code? Thank you in advance.
Java Code:
package musicplayer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Wrapper {
public static ArrayList<String> search(String searchTerm) throws IOException {
String projectDirectory = System.getProperty("user.dir");
ArrayList<String> result = new ArrayList<>();
String[] commands = {"python", "'" + projectDirectory + "\\src\\python\\search.py'", "--q","\'"+ searchTerm +"\'"};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = "";
while ((line = stdInput.readLine()) != null)
result.add(line);
return result;
}
public static void main(String[] args) {
try {
System.out.println(search("foo"));
} catch (IOException exc) {
exc.printStackTrace();
}
}
}
Python Script:
#!/usr/bin/python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.tools import argparser
# valid developer key
DEVELOPER_KEY = "AIzaSyDvIqgHz4EQBm3qPRdonottrythisoneQ0W0Wooh5gYPQ8"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=options.q,
part="id,snippet",
maxResults=options.max_results
).execute()
videos = []
channels = []
playlists = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["videoId"]))
elif search_result["id"]["kind"] == "youtube#channel":
channels.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["channelId"]))
elif search_result["id"]["kind"] == "youtube#playlist":
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["playlistId"]))
print("Videos:\n", "\n".join(videos), "\n")
print("Channels:\n", "\n".join(channels), "\n")
print("Playlists:\n", "\n".join(playlists), "\n")
if __name__ == "__main__":
searchString = ''
argparser.add_argument("--q", help=searchString, default=searchString)
argparser.add_argument("--max-results", help="Max results", default=25)
args = argparser.parse_args()
try:
youtube_search(args)
except HttpError as e:
print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
Related
I have a file try.java which has the following code. I have a space-separated string which I should pass as an argument to execute another python code test.py. Is there any easier way to access the whole string as a single argument rather than to iterate through every argument using
sys.argv[1] in python code to get all the arguments as one string? Currently, I am doing this...
test.py
import sys
lst = [' {0} '.format(elem) for elem in sys.argv[1:]]
str1 = ''.join(str(e) for e in lst)
print(str1)
try.java
import java.util.*;
import java.io.*;
class Try{
public static void main(String a[]) {
try {
String s = "space separated string";
Process p = Runtime.getRuntime().exec("python3 test.py " + s);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = (in.readLine());
System.out.println("value is : " + ret);
} catch (Exception e) {
}
}
}
Any explanation with some Reference would be helpful.
I'm building a simple class in Java that return the serial number of disk of computer. So this is the code:
package utility;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestReadSerialNumber {
private TestReadSerialNumber() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber"; // see note
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = TestReadSerialNumber.getSerialNumber("C");
System.out.println(sn);}
}
Now if I try to start this code from a Windows, I have the correct result. If I try to start this code on a Mac Computer, I don't have never string from getSerialNumber method.
I think that the problem is in the System Operation and my code is compatible only with Windows and not with Mac.
Then, how can I get the serial number by Mac computer ?
I have written a class to ping an IP address that i provide, but it won't return anything.
I tried adding a few markers to see where it goes wrong, but not even that worked...
I have a gui interface and I use a Label to write my data out (the same format worked before with a string), here is the code. There were certain lines that i did or did not want, hence the "relevant" integer, you may ignore it. This should run on ubuntu 13.10.
public static ArrayList<String> PingIpAddr(String string) throws IOException{
String s = new String();
int relevant =0;
ArrayList<String> List = new ArrayList<String>();
List.add("it happens \n");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(new ProcessBuilder(string).start().getInputStream()));
while ((s = stdInput.readLine()) != null){
List.add("does this happen? \n");
relevant++;
if( (relevant == 2) || (relevant == 3) || (relevant == 4) || (relevant == 5) || (relevant == 6) || (relevant == 9) ){List.add(s + "\n");
List.add("or this? \n");}} //end of while
List.add("This must happen! \n");
return List;} //end of Ping
and if this would work, here is where it would be implemented:
String test;
test = PingIp.testPingIpAddr("ping -c 5 4.2.2.2").toString();
TeltonikaPing.setWrapText(true);
TeltonikaPing.setText(test);
Strangely it doesn't give back a sigle line. Maybe I'm just missing something very basic?:/
the main issue is caused by the fact ping has a delay in most cases, try making use of stdInput.ready().
I would probably pass this to ProcessBuilder: new ProcessBuilder("myCommand", "myArg1", "myArg2"); split out the command ping from its parameters.
as in - http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
I hope this helps (:
Edit -- (this works below)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Pinger
{
public static List<String> PingIpAddr(String ip) throws IOException
{
ProcessBuilder pb = new ProcessBuilder("ping", ip);
//ProcessBuilder pb = new ProcessBuilder("ping", "-c 5", ip);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(pb.start().getInputStream()));
while (!stdInput.ready())
{
// custom timeout handling
}
String line;
ArrayList<String> output = new ArrayList<>();
while ((line = stdInput.readLine()) != null)
{
output.add(line);
}
return output;
}
public static void main(String[] args) throws IOException
{
List<String> lines = Pinger.PingIpAddr("127.0.0.1");
for (String line : lines)
{
System.out.println(line);
}
}
}
I found a nother solution, that lets me enter how long i want the Ping to be.
How to run PING command and get ping host summary?
if anyone else needs to incorporate it into a GUI :)
I have some content in an input file a.txt as
Line 1 : "abcdefghijk001mnopqr hellohello"
Line 2 : "qwertyuiop002asdfgh welcometologic"
Line 3 : "iamworkingherefromnowhere002yes somethingsomething"
Line 4 : "thiswillbesolved001here ithink"
I have to read the a.txt file and write it to two separate files. ie., lines having 001 should be written to output1.txt and lines having 002 should be written to output2.txt
Can someone help me on this with a logic in Java programming.
Thanks,
Naren
BufferedReader br = new BufferedReader( new FileReader( "a.txt" ));
String line;
while(( line = br.readLine()) != null ) {
if( line.contains( "001" )) sendToFile001( line );
if( line.contains( "002" )) sendToFile002( line );
}
br.close();
The method sendToFile001() and sendToFile002() write the parameter line as follow:
ps001.println( line );
with ps001 and ps002 of type PrintStream, opened before (in a constructor?)
Here is a good example for Reading and writing text files using Java and checking conditions do the following
while ((line = reader.readLine()) != null) {
//process each line in some way
if(line.contains("001") {
fileWriter1.write(line);
} else if (line.contains("002") ) {
fileWriter2.write(line);
}
}
Code complete.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
/**
*
* #author andy
*/
public class JFile {
/**
* #param args the command line arguments
*/
static File master = null,
m1 = null, // file output with "001"
m2 = null; // file output with "002"
static FileWriter fw1,
fw2;
static FileReader fr = null;
static BufferedReader br = null;
public static void main(String[] args) throws FileNotFoundException, IOException
{
String root = System.getProperty("user.dir") + "/src/files/";
master = new File ( root + "master.txt" );
m1 = new File ( root + "m1.txt");
m2 = new File ( root + "m2.txt");
fw1 = new FileWriter(m1, true);
fw2 = new FileWriter(m2, true);
fr = new FileReader (master);
br = new BufferedReader(fr);
String line;
while((line = br.readLine())!=null)
{
if(line.contains("001"))
{
fw1.write(line + "\n");
} else if (line.contains("002"))
{
fw2.write(line + "\n");
}
}
fw1.close();
fw2.close();
br.close();
}
}
Project Netbeans : http://www.mediafire.com/?yjdtxj2gh785cyd
I have a hdd array with 4 encrypted hard-drives (truecrypt). I recently switched back from 5 years of linux to windows 7 and I find myself confronted with a problem I can't find a solution for.
Under linux there was a command called "fdisk" which gives you all running (not mounted!) harddrives plus a unique disk-identifier which doesn't change (something like: Disk Identifier: 00x33f1a3c1).
I need that same functionality under Windows, preferably writing the code in java.
cheers
edit:// For clarification, I need the Disk-ID without mounting the Disk!
A solution using VBS.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DiskUtils {
private DiskUtils() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = DiskUtils.getSerialNumber("C");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, sn, "Serial Number of C:",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}