How do I terminate a shell program through python - python

Let's say I do somthing like this:
import os
os.system('java some_program.jar')
Is there a way to stop the execution of that program through python?
My situation:
I have a program in java that does some stuff and inserts data into a .csv file and I need to run it through python (because I'm using python for handeling the data in the .csv file) but the program itself doesn't stop by itself so i need a way to stop it manually once it inserts the data into the .csv file

Don't use os.system.
Instead, use p = subprocess.Popen(...). Then simply call p.kill().
Also, your Java program should be updated to exit when it sees EOF on stdin.

You could try having the java program echo to console or something that it is finished writing to the CSV file using the subprocesses library and it's check_output function. And when that is done, use something like this: os.system("taskkill /im some_program.jar") to kill off the program.

Related

Python subprocess.run C Program not working

I am trying to write the codes to run a C executable using Python.
The C program can be run in the terminal just by calling ./myprogram and it will prompt a selection menu, as shown below:
1. Login
2. Register
Now, using Python and subprocess, I write the following codes:
import subprocess
subprocess.run(["./myprogram"])
The Python program runs but it shows nothing (No errors too!). Any ideas why it is happening?
When I tried:
import subprocess
subprocess.run(["ls"])
All the files in that particular directory are showing. So I assume this is right.
You have to open the subprocess like this:
import subprocess
cmd = subprocess.Popen(['./myprogram'], stdin=subprocess.PIPE)
This means that cmd will have a .stdin you can write to; print by default sends output to your Python script's stdout, which has no connection with the subprocess' stdin. So do that:
cmd.stdin.write('1\n') # tell myprogram to select 1
and then quite probably you should:
cmd.stdin.flush() # don't let your input stay in in-memory-buffers
or
cmd.stdin.close() # if you're done with writing to the subprocess.
PS If your Python script is a long-running process on a *nix system and you notice your subprocess has ended but is still displayed as a Z (zombie) process, please check that answer.
Maybe flush stdout?
print("", flush=True,end="")

Python redirect output after os._exit

I have thread which is supposed to close whole application, so I use os._exit(1). But I also want to redirect output from my program to file and the output file is empty after all. Simple example:
import os
print('something')
os._exit(1)
Running program with:
python myprogram.py > output.txt
Is there any way to do this?

Start job from python, redirect output to file

I have a script, update_file, that I typically run like so:
sudo update_file (file) > ./logs/(file) &
I was wondering what the proper syntax/is it possible, to call this script from within a Python script and still have it redirect output from update_file to a file and have it created as a system job.
EDIT: I should note, I run this against multiple (file)s so I would like to pass that as a variable.
import subprocess
subprocess.call("sudo update_file(file)",stdout=open("logs/(file)","w"))
maybe?
First, the subprocess module is how you execute programs from Python. The section Replacing Older Functions with the subprocess Module in the documentation shows you how to transform typical shell functionality into Python.
Because you're using & to background the task, you'll want to create a Popen, and do the job-handling later. So:
jobs = []
# ... each time you want to run it on a file ...
jobs.append(subprocess.Popen(['sudo', 'update_file', file],
stdout=open(os.path.join('logs', file), 'w'))
# ... at exit time ...
for job in jobs:
job.wait()
job.stdout.close()

Run a python script in perl

I have two scripts, a python script and a perl script.
How can I make the perl script run the python script and then runs itself?
Something like this should work:
system("python", "/my/script.py") == 0 or die "Python script returned error $?";
If you need to capture the output of the Python script:
open(my $py, "|-", "python2 /my/script.py") or die "Cannot run Python script: $!";
while (<$py>) {
# do something with the input
}
close($py);
This also works similarly if you want to provide input for the subprocess.
The best way is to execute the python script at the system level using IPC::Open3. This will keep things safer and more readable in your code than using system();
You can easily execute system commands, read and write to them with IPC::Open3 like so:
use strict;
use IPC::Open3 ();
use IO::Handle (); #not required but good for portabilty
my $write_handle = IO::Handle->new();
my $read_handle = IO::Handle->new();
my $pid = IPC::Open3::open3($write_handle, $read_handle, '>&STDERR', $python_binary. ' ' . $python_file_path);
if(!$pid){ function_that_records_errors("Error"); }
#read multi-line data from process:
local $/;
my $read_data = readline($read_handle);
#write to python process
print $write_handle 'Something to write to python process';
waitpid($pid, 0); #wait for child process to close before continuing
This will create a forked process to run the python code. This means that should the python code fail, you can recover and continue with your program.
It may be simpler to run both scripts from a shell script, and use pipes (assuming that you're in a Unix environment) if you need to pass the results from one program to the other

Python: How to execute an external program

How do I execute a program from within my program without blocking until the executed program finishes?
I have tried:
os.system()
But it stops my program till the executed program is stopped/closed. Is there a way to allow my program to keep running after the execution of the external program?
Consider using the subprocess module.
Python 2: http://docs.python.org/2/library/subprocess.html
Python 3: http://docs.python.org/3/library/subprocess.html
subprocess spawns a new process in which your external application is run. Your application continues execution while the other application runs.
You want subprocess.
You could use the subprocess module, but the os.system will also work. It works through a shell, so you just have to put an '&' at the end of your string. Just like in an interactive shell, it will then run in the background.
If you need to get some kind of output from it, however, you will most likely want to use the subprocess module.
You can use subprocess for that:
import subprocess
import codecs
# start 'yourexecutable' with some parameters
# and throw the output away
with codecs.open(os.devnull, 'wb', encoding='utf8') as devnull:
subprocess.check_call(["yourexecutable",
"-param",
"value"],
stdout=devnull, stderr=subprocess.STDOUT
)

Categories

Resources