1

I want to debug a small python script that takes input from stdin and sends it to stdout. Used like this:

filter.py < in.txt > out.txt

There does not seem to be a way to configure Pycharm debugging to pipe input from my test data file.

This question has been asked before, and the answer has been, basically "you can't--rewrite the script to read from a file."

I modified the code to take a file, more or less doubling the code size, with this:

import argparse

if __name__ == '__main__':
    cmd_parser = argparse.ArgumentParser()
    cmd_parser.add_argument('path', nargs='?', default='/dev/stdin')
    args = cmd_parser.parse_args()
    with open(in_path) as f:
        filter(f)

where filter() now takes a file object open for write as a parameter. This permits backward compatibility so it can be used as above, while I am also able to invoke it under the debugger with input from a file.

I consider this an ugly solution. Is there a cleaner alternative? Perhaps something that leaves the ugliness in a separate file?

1 Answer 1

1

If you want something simpler, you can forgo argparse entirely and just use the sys.argv list to get the first argument.

import sys

if len(sys.argv) > 1:
    filename = sys.argv[1]
else:
    filename = sys.stdin

with open(filename) as f:
    filter(f)
Sign up to request clarification or add additional context in comments.

2 Comments

I assume the preceding would need the if __name__ == '__main__': bit when merged with the def filter(file): definition (filter() def not shown in my example either).
Yes, you can nest the above code under the if __name__ == '__main__' block so that it only runs when called as a script and not when imported as a module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.