Home > Software engineering >  Run python code with sys.stdin using my own inputs
Run python code with sys.stdin using my own inputs

Time:09-01

Hi I have a very naive question.

I have this piece of python code test.py that I am trying to test run. May I know how do I run it using my own inputs?

I tried running it on my command line using python3 test.py ABCD but the command line does not return anything..

I have also tried python3 test.py ABCD.txt where ABCD.txtcontains the line ABCD but also to no avail...

Any help would be greatly appreciated, thank you.

import sys
output = []
for ln in sys.stdin:
   for c in ln:
      if c in 'ABCD':
           output.append(c)
sys.stdout.write(''.join(output)   '\n')

CodePudding user response:

python3 test.py < ABCD.txt as suggested by keith works, thank you everyone!

CodePudding user response:

Running the code like python code.py a b c d will result in storing a, b, c, and d as input command line arguments. So to handle that you need to use sys.argv and edit the code as follows.

import sys
output = []
for ln in sys.argv:
   for c in ln:
      if c in 'ABCD':
           output.append(c)
sys.stdout.write(''.join(output)   '\n')

check here for more info.

However, all standard inputs to an application are handled using < command. Just like the standard output which is handled by >. So to run the just add < like :python3 test.py < ABCD and it should be ok.

  • Related