Search code examples
pythonpython-2.7pycharm

How do I access sys.stdin when running a script in PyCharm console mode


This works when I run it in PyCharm (v2020.1) terminal, but when I run it through the console, it just hangs:

#test.py

import sys

txt = sys.stdin
print(txt.read())
# readme.txt

random string

The run configuration


Solution

  • In the run configurations dialogue the Parameters field is where command line arguments are specified to be passed to the script that can then be accessed using sys.argv. To get the input from sys.stdin you would use the Redirect input from field.

    The usual shell redirection functionalities each have their own field (notice they can be different between shells, compare for example with Windows CMD). With each functionality corresponding to one field, Redirect input from, Before launch which is equivalent to running a command before redirecting the input, the Logs tab for redirecting results to output, etc...

    This is convenient for a couple of reasons. First because it gives you the shell syntax in a structured way that dispenses having to write everything on a single line (contrary to writing directly on the command line). Second, because you may be working on a project with developers who use different shells/OS's (or want to test different shells yourself) so using the run/configurations dialogue allows to abstract differences in shell syntax and reuse or share the "run configurations" if you want.