Search code examples
pythoncondauser-input

EOL error from input() when running python script using shebang that specifies a conda environment


I am making a python CLI that prompts user to enter input at certain times during its running. I want to use the input function for this but get EOFError: EOF when reading a line when it reaches the input() line.

I've done some testing and I think the problem is I am using a shebang on the script that makes it run with a specific condo environment. This is the minimal code needed to reproduce the problem

#!/usr/bin/env conda run -n TEST python

def main(): # testing
    chromatogram_result = input()
    print(chromatogram_result)

if __name__ == "__main__":
    main()

where TEST is my conda environment name.

The issue occurs if I run this from the command line by simply invoking the file name

$ ./my_file.py

It also occurs if I run it from terminal using a command based on the shebang

$ conda run -n TEST python my_file.py

But doesn't occur if I activate the correct conda environment and then run it

$ conda activate TEST
$ python3 my_file.py

My question is why is this occurring and is there a better way to invoke a specific conda environment in a shebang to avoid this? Or do I have to use a normal shebang and remember to activate my environment each time I want to use the script?

This is on macOS 10.14.6, using conda 4.10.3. It doesn't seem specific to one conda environment, I've tried a few different ones on my system and all give the same error with this shebang


Solution

  • By default Conda buffers I/O on conda run. You'll need the --no-capture-output flag to get interactive I/O:

    #!/usr/bin/env conda run -n TEST --no-capture-output python
    
    def main(): # testing
        chromatogram_result = input()
        print(chromatogram_result)
    
    if __name__ == "__main__":
        main()
    

    As for whether there is a better way: no, this is the best pattern I've seen for creating executable Python scripts that evaluate in specific Conda environments.