Summary I would like to write python scripts that act like bash scripts on the command line, but then I would also like to easily compile them in python. Where I have problems, this is the glue to do the last.
So imagine that I wrote two scripts, script1.py and script2.py , and I can combine them like this:
echo input_string | ./script1.py -a -b | ./script2.py -c -d
How to get this behavior from another python file? That's how I know, but I don't like it:
arg_string_1 = convert_to_args(param_1, param_2) arg_string_2 = convert_to_args(param_3, param_4) output_string = subprocess.check_output("echo " + input_string + " | ./script1.py " + arg_string_1 + " | ./script2.py " + arg_string_2)
If I did not want to use multithreading, I could do something like this (?):
input1 = StringIO(input_string) output1 = StringIO() script1.main(param_1, param_2, input1, output1) input2 = StringIO(output1.get_value()) output2 = StringIO() script2.main(param_3, param_4, input2, output2)
Here's the approach I tried, but I'm stuck in writing glue. I would appreciate that I learned how to complete my approach below, or suggestions for a better design / approach!
My approach: I wrote script1.py and script2.py to look like this:
#!/usr/bin/python3 ... # import sys and define "parse_args" def main(param_1, param_2, input, output): for line in input: ... print(stuff, file=output) if __name__ == "__main__": parameter_1, parameter_2 = parse_args(sys.argv) main(parameter_1, parameter_2, sys.stdin, sys.stdout)
Then I wanted to write something like this, but I donβt know how to finish:
pipe_out, pipe_in = ???? output = StringIO() thread_1 = Thread(target=script1.main, args=(param_1, param_2, StreamIO(input_string), pipe_out)) thread_2 = Thread(target=script2.main, args=(param_3, param_4, pipe_in, output) thread_1.start() thread_2.start() thread_1.join() thread_2.join() output_str = output.get_value()