I have a piece of python code, that I need to convert it to perl, but unfortunately I am not good in perl, so sorry if the question is simple. I would like to check STDOUT and STDERR for a specific word. Here is the python code:
p = subprocess.Popen("bmod -b " + beginTime + " " + job_id + "; exit 1;",
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
while p.poll() is None:
err = p.stderr.readline().decode('utf_8')
out = p.stdout.readline().decode('utf_8')
if "changed" in err or "changed" in out:
subprocess.Popen("echo rescheduling was successful!", shell=True)
os._exit(0)
I read some documentations and open3 function may work here, but for p.poll() part I am not sure what to use.
The answer depends on if it is important to print the message
"rescheduling was successful!"
immediately after a the line was printed frombmod
(whenbmod
is still running) or if it is sufficient to print the line afterbmod
has exited.The last case is a very simple to achieve in Perl, for example:
Regarding the first case, if you need to print the message immediately (even before
bmod
has exited), first note that your Python script is probably not working correctly. The linesp.stderr.readline()
will block the script until a line is ready to be read fromp.stderr
, similarlyp.stdout.readline()
will block the script until a line is ready to be read fromp.stdout
. So ifbmod
only prints tostdout
and nothing goes tostderr
, the script will hang at the first call top.stderr.readline()
and only return whenbmod
exits.I am not sure how to do this correctly in Python, but in Perl you can use
IPC::Open3
combined withIO::Select
. See for example: Perl select return “bad file descriptor” errorAlso note: A simpler solution in Perl can be achived using
open
ifstderr
andstdout
are merged: