I am running a python script from Groovy via:
Process p = Runtime.getRuntime().exec("python /Users/afrieden/Projects/hgvs/hgvs/tests/test_gsg_variants.py");
String s = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
However it calls what looks like a cython library seqfmt. (seqfmt.c and seqfmt.pyx).
I have added it in the sys import:
import sys
sys.path.append("/Users/afrieden/Projects/hgvs/build/lib/")
sys.path.append("/Users/afrieden/pythonLib/pygr-0.8.2/")
sys.path.append("/Users/afrieden/pythonLib/pygr-0.8.2/pygr/seqfmt.pyx")
sys.path.append("/Users/afrieden/pythonLib/pygr-0.8.2/pygr/seqfmt.c")
import hgvs
import csv
import hgvs.utils
from pygr.seqdb import SequenceFileDB
Any thoughts on how I can get it to run? Thanks!
EDIT:
It does work with python from the command line just fine.
Simplifying your script slightly, does this work:
def proc = [ 'bash', '-c', 'python /Users/afrieden/Projects/hgvs/hgvs/tests/test_gsg_variants.py' ].execute()
StringWriter out = new StringWriter()
StringWriter err = new StringWriter()
proc.waitForProcessOutput( out, err )
println 'Here is the standard output of the command:'
println out.toString()
println 'Here is the standard error of the command (if any):'
println err.toString()
Related
I want to start a python program from inside a scala program that has to receive a possibly infinitely long string. Thus it is not possible to pass it as a cmd argument.
My solution is to transmit the data via the stdstreams. However, I am unable to find the scala version of the working bash code:
bash code:
#/bin/bash
var="SOME REALLY LONG STRING THAT IS SEND TO THE PYTHON PROGRAM"
echo "$var" | ./readUntilEOF.py
scala code:
import sys.process._
object main {
def main(args : Array[String]) : Unit = {
val cmd = "./readUntilEOF.py"
val string = "SOME REALLY LONG STRING THAT IS SEND TO THE PYTHON PROGRAM"
print("I am starting to send stuff...")
val resultString = (string #| cmd.!!).!!
print(resultString)
}
}
readUntilEOF.py:
#!/usr/bin/python3
import sys
if __name__ == "__main__":
read = sys.stdin.read()
print(read)
Output running the bash command:
#> ./scalaBashEquivalent.sh
SOME REALLY LONG STRING THAT IS SEND TO THE PYTHON PROGRAM
Output running the scala code:
#> scala scala.sc
I am starting to send stuff...
/* and then it never terminates */
#< can take InputStream so try
(cmd #< new ByteArrayInputStream(string.getBytes)).!!
scastie
It is indeed a bit more complex than expected. But the below code seems to work.
import java.io.PrintWriter
object main {
def main(args : Array[String]) : Unit = {
val cmd = "./readUntilEOF.py"
val string = "SOME REALLY LONG STRING THAT IS SEND TO THE PYTHON PROGRAM"
println("I am starting to send stuff...")
val processOutput : StringBuilder = new StringBuilder()
val process = Process(cmd).run(new ProcessIO(
in => {
val writer = new PrintWriter(in)
writer.write(string)
writer.close()
},
out => {
processOutput.addAll(scala.io.Source.fromInputStream(out))
out.close()
},
_.close()
))
assert(process.exitValue() == 0)
print(processOutput.toString)
}
}
I have a web interface built with Spring and I want to execute the command "python file.py" from it.
The main problem is that inside the file.py there is a pyomo model that is supposed to give some output. I can execute a python script if it's a simple print or something, but the pyomo model is completely ignored.
What could be the reason?
Here is the code I wrote in the controller to execute the call:
#PostMapping("/execute")
public void execute(#ModelAttribute("component") #Valid Component component, BindingResult result, Model model) {
Process process = null;
//System.out.println("starting!");
try {
process = Runtime.getRuntime().exec("python /home/chiara/Documents/GitHub/Pyomo/Solver/test/sample.py");
//System.out.println("here!");
} catch (Exception e) {
System.out.println("Exception Raised" + e.toString());
}
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println("stdout: " + line);
}
} catch (IOException e) {
System.out.println("Exception in reading output" + e.toString());
}
}
Update: I found that what I was missing was that I didn't check where the code run. So be sure to do so and eventually move the input files (if you have any) in the directory where python is executing, otherwise the script can't find them and elaborate them.
You can use
cwd = os.getcwd()
to check the current working directory of a process.
Another possibility is to redirect the stderr on the terminal or in a log file, because from the Server terminal you won't see anything even if there are errors.
The code posted in the question is the correct way to invoke a bash command from java.
I have the following perl module for wrapping CORE::system in perl scripts:
package system_wrapper;
sub check_system {
my ($cmd) = #_;
my $err = CORE::system($cmd);
if ($err != 0) {
print "Error occured when executing: $cmd. Exiting.\n";
exit(-1);
}
}
*CORE::GLOBAL::system = \&check_system;
1;
__END__
I'm attempting to acheive the same thing in python. I can't work out how to extend the syntax described here using decorators to this os method.
I would like calls to the wrapped method to be exactly the same as the unwrapped.
i.e. status = os.system("mycmd" + " myarg")
You can just monkey patch os.system. Rename the real os.system to something else,
then create a function using it and assign it to os.system:
def my_os_system(cmd):
err = os._system(cmd)
if err != 0:
print "Error occured when executing: %s. Exiting." % cmd
sys.exit(-1)
os._system = os.system
os.system = my_os_system
I cannot figure out how I can execute a python script from my C code. I read that I can embed the python code inside C, but I want simply to launch a python script as if I execute it from command line. I tried with the following code:
char * paramsList[] = {"/bin/bash", "-c", "/usr/bin/python", "/home/mypython.py",NULL};
pid_t pid1, pid2;
int status;
pid1 = fork();
if(pid1 == -1)
{
char err[]="First fork failed";
die(err,strerror(errno));
}
else if(pid1 == 0)
{
pid2 = fork();
if(pid2 == -1)
{
char err[]="Second fork failed";
die(err,strerror(errno));
}
else if(pid2 == 0)
{
int id = setsid();
if(id < 0)
{
char err[]="Failed to become a session leader while daemonising";
die(err,strerror(errno));
}
if (chdir("/") == -1)
{
char err[]="Failed to change working directory while daemonising";
die(err,strerror(errno));
}
umask(0);
execv("/bin/bash",paramsList); // python system call
}
else
{
exit(EXIT_SUCCESS);
}
}
else
{
waitpid(pid1, &status, 0);
}
I don't know where the error is since if I replace the call to python script with the call to another executable, it works well.
I have added at the beginning of my python script the line:
#!/usr/bin/python
What can I do?
Thank you in advance
From the Bash man page:
-c string If the -c option is present, then commands are read
from string. If there are arguments after the string,
they are assigned to the positional parameters,
starting with $0.
E.g.
$ bash -c 'echo x $0 $1 $2' foo bar baz
x foo bar baz
You, however don’t want to assign to the positional parameters, so change your paramList to
char * paramsList[] = { "/bin/bash", "-c",
"/usr/bin/python /home/mypython.py", NULL };
Using char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL}; and execv("/usr/bin/python",paramsList); // python system call caused a successful invocation of the python script named bla.py
I have a simple Python script that asks for your name, then spits it back out:
def main():
print('Enter your name: ')
for line in sys.stdin:
print 'You entered: ' + line
Pretty simple stuff! When running this in the OS X Terminal, it works great:
$ python nameTest.py
Enter your name:
Craig^D
You entered: Craig
But, when attempting to run this process via an NSTask, the stdout only appears if additional flush() calls are added to the Python script.
This is how I have my NSTask and piping configured:
NSTask *_currentTask = [[NSTask alloc] init];
_currentTask.launchPath = #"/usr/bin/python";
_currentTask.arguments = [NSArray arrayWithObject:#"nameTest.py"];
NSPipe *pipe = [[NSPipe alloc] init];
_currentTask.standardOutput = pipe;
_currentTask.standardError = pipe;
dispatch_queue_t stdout_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
__block dispatch_block_t checkBlock;
checkBlock = ^{
NSData *readData = [[pipe fileHandleForReading] availableData];
NSString *consoleOutput = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
dispatch_sync(dispatch_get_main_queue(), ^{
[self.consoleView appendString:consoleOutput];
});
if ([_currentTask isRunning]) {
[NSThread sleepForTimeInterval:0.1];
checkBlock();
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
NSData *readData = [[pipe fileHandleForReading] readDataToEndOfFile];
NSString *consoleOutput = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
[self.consoleView appendString:consoleOutput];
});
}
};
dispatch_async(stdout_queue, checkBlock);
[_currentTask launch];
But when running the NSTask, this is how it appears (it is initially blank, but after entering my name and pressing CTRL+D, it finishes all at once):
Craig^DEnter your name:
You entered: Craig
So, my question is: How can I read the stdout from my NSTask without requiring the additional flush() statements in my Python script? Why does the Enter your name: prompt not appear immediately when run as an NSTask?
When Python sees that its standard output is a terminal, it arranges to automatically flush sys.stdout when the script reads from sys.stdin. When you run the script using NSTask, the script's standard output is a pipe, not a terminal.
UPDATE
There is a Python-specific solution to this. You can pass the -u flag to the Python interpreter (e.g. _currentTask.arguments = #[ #"-u", #"nameTest.py"];), which tells Python not to buffer standard input, standard output, or standard error at all. You can also set PYTHONUNBUFFERED=1 in the process's environment to achieve the same effect.
ORIGINAL
A more general solution that applies to any program uses what's called a “pseudo-terminal” (or, historically, a “pseudo-teletype”), which we shorten to just “pty”. (In fact, this is what the Terminal app itself does. It is a rare Mac that has a physical terminal or teletype connected to a serial port!)
Each pty is actually a pair of virtual devices: a slave device and a master device. The bytes you write to the master, you can read from the slave, and vice versa. So these devices are more like sockets (which are bidirectional) than like pipes (which are one-directional). In addition, a pty also let you set terminal I/O flags (or “termios”) that control whether the slave echoes its input, whether it passes on its input a line at a time or a character at a time, and more.
Anyway, you can open a master/slave pair easily with the openpty function. Here's a little category that you can use to make an NSTask object use the slave side for the task's standard input and output.
NSTask+PTY.h
#interface NSTask (PTY)
- (NSFileHandle *)masterSideOfPTYOrError:(NSError **)error;
#end
NSTask+PTY.m
#import "NSTask+PTY.h"
#import <util.h>
#implementation NSTask (PTY)
- (NSFileHandle *)masterSideOfPTYOrError:(NSError *__autoreleasing *)error {
int fdMaster, fdSlave;
int rc = openpty(&fdMaster, &fdSlave, NULL, NULL, NULL);
if (rc != 0) {
if (error) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil];
}
return NULL;
}
fcntl(fdMaster, F_SETFD, FD_CLOEXEC);
fcntl(fdSlave, F_SETFD, FD_CLOEXEC);
NSFileHandle *masterHandle = [[NSFileHandle alloc] initWithFileDescriptor:fdMaster closeOnDealloc:YES];
NSFileHandle *slaveHandle = [[NSFileHandle alloc] initWithFileDescriptor:fdSlave closeOnDealloc:YES];
self.standardInput = slaveHandle;
self.standardOutput = slaveHandle;
return masterHandle;
}
#end
You can use it like this:
NSTask *_currentTask = [[NSTask alloc] init];
_currentTask.launchPath = #"/usr/bin/python";
_currentTask.arguments = #[[[NSBundle mainBundle] pathForResource:#"nameTest" ofType:#"py"]];
NSError *error;
NSFileHandle *masterHandle = [_currentTask masterSideOfPTYOrError:&error];
if (!masterHandle) {
NSLog(#"error: could not set up PTY for task: %#", error);
return;
}
Then you can read from the task and write to the task using masterHandle.