0

I am writing a program in python to search my .bib-files for LaTeX with several flags. For that purpose I am using the argparse package for python.

parser = argparse.ArgumentParser(description=description_string, usage=usage_string, add_help=True)
parser.add_argument("-f", "--file", type=str, help=file_help_text)
parser.add_argument("-s", "--signifier", type=str, action='append',help=signifier_help_text)
parser.add_argument("-a", "--attribute", type=str, help=attribute_help_text)
parser.add_argument("-q", "--query", type=str, help=query_help_text)
args = parser.parse_args()

Since I want to be able to use the program in the terminal, want to be able to pipe information from other processes to the script. Specifically, I want any string piped to the script to be used as the input to the -q / --query option of my script.

I have already read the following question and it did not solve my problem: Bash pipe to python

How can I control to which input-flag the piped strings go? Is there a package for it? It would really make my script more useful if I could pip into it.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Enemoy
  • 11
  • 3
  • If you want to pipe them I think you'll have to write your own parser ... you could, alternatively, use `./my_script.py --some param --query $( my_bash_script )` ... – tink Dec 04 '21 at 17:26
  • Well, this is a bit clunky, but it works, if I put " " around the argument. Thank you! I will see, if a parser is worth the effort. – Enemoy Dec 04 '21 at 17:33
  • 1
    `argparse` parses `sys.argv`. Piped data is read from `sys.stdin`, as shown in the link. Those are different sources. – hpaulj Dec 04 '21 at 17:41

1 Answers1

0

You can get argparse to take input from somewhere else than sys.argv. Perhaps first check if there's standard input. If not, prepare argument list arglist equal to sys.argv or its useful part. If yes, make it sys.argv with appended 1 line read from standard input.

import sys

arglist = sys.argv[1:]
if not sys.stdin.isatty():
    query = sys.stdin.read(1)
    arglist.append(query) #or perhaps "--query "+query

Finally, parse it like usual, but with arglist as a parameter:

args = parser.parse_args(arglist)
Minty
  • 78
  • 1
  • 7