Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse optional stdin read and/or stdout out

A non-Python program will call a Python program with both input and output arguments. Input may be a file reference or a string redirected to stdin in the non-Python program. Output may be a file or stdout.

argparse.FileType seems ready to handle this as it already has the special - to direct to stdin/stdout. In fact, using - to direct to stdout works but the implementation/syntax for stdin is what I don't know.

Examples calls in the non-Python code:
python mycode.py - output.txt
python mycode.py - -

What does the non-Python code do after that? Print/stdout an input string?
What does the Python code do after that?

I will always need to distinguish where both args are going (i.e. input and output) so using default="-" nor default=sys.stdin in add_argument won't work because they require an absent argument.

Here's what I have so far:

parser = argparse.ArgumentParser()

parser.add_argument('read_fref', type=argparse.FileType('r'))
parser.add_argument('write_fref', type=argparse.FileType('w'))
parser_ns = parser.parse_args()

with parser_ns.read_fref as f_r:
    read_f = json.load(f_r)    

output = {'k': 'v'}

with parser_ns.write_fref as f_w:
    json.dump(output, f_w)
like image 312
Eric S Avatar asked Mar 15 '23 11:03

Eric S


1 Answers

I'm having trouble understanding what you are asking. I understand what Python and argparse are doing, but I don't quite understand what you are trying to do.

Your sample looks like it would run fine when called from a Linux shell. With the the - arguments, it should accept input from the keyboard, and display it on the screen. But those arguments are most often used with shell redirection controls >, <, | (details vary with shell, sh, bash, etc).

But if you are using the shell to redirect stdin or stdout to/from files, you could just as well give those files as commandline arguments.

If you are bothered by required/default issue, consider making these arguments flagged (also called optionals):

parser.add_argument('-r','--readfile', type=argparse.FileType('r'), default='-')
parser.add_argument('-w','--writefile', type=argparse.FileType('w'), default='-')

With this change, these calls are the same

python mycode.py -r - <test.json
python mycode.py <test.json
python mycode.py -r test.json

all writing to the screen (stdout). That could be redirected in similar ways.

To take typed input:

python mycode.py
{...}
^D
like image 113
hpaulj Avatar answered Mar 24 '23 00:03

hpaulj