0

I have a python function that suppose to take "sys.stdin" as input in a .py script like

...
output = function_name (sys.stdin)
...

Now if I want to test this function with a python shell command, how can I provide a "sys.stdin" as if the python shell could recognize a bash command like

>>> output = function_name (cat some_file | head -1)
zhihao_li
  • 183
  • 10
  • what testing framework are you using? – gold_cy Jan 29 '20 at 21:40
  • This seems like a rather common question, have you done any research? – AMC Jan 29 '20 at 21:42
  • 2
    Do you need to test `function_name`, or code that calls `function_name` with `sys.stdin` as an argument? If the former, you can pass any file-like object (including `io.StringIO`) as an argument. If the latter, you'll probably need to patch something, though that could be as easy as assigning a new file-like object to `sys.stdin` (`sys.stdin = io.StringIO("...")`). – chepner Jan 29 '20 at 21:43
  • One certainly *can* run `p = subprocess.Popen(['head', '-n', '1'], stdin=open('some_file', 'r'), stdout=subprocess.PIPE)` and then `output = function_name(p.stdout)`, but the `cat some_file | head -1` example is silly -- there's no reason to use `head` at all, since Python itself can read a line from a file trivially (and then expose that as a file using `StringIO` as chepner shows), and even if you *were* going to use `head`, there's still no reason to use `cat` (that's true even in shell; more efficient to `head -1 – Charles Duffy Jan 29 '20 at 21:50
  • Thanks, I am testing the latter. – zhihao_li Jan 29 '20 at 21:50

0 Answers0