Skip to content
Advertisement

Invoke Python as Executable

I have a Python script, a simple Hello, World. I need to invoke it as I would an executable and take piped input:

./myprogram < myinput

How do I generate the command python3 myprogram.py and handle the piped input?

Advertisement

Answer

If you’re on a *Nix system, you’ll need to follow 3 steps:

  1. Make sure your script has executable permissions

    chmod +x myprogram.py
    
  2. Add the shebang line to the top of your script

    #!/usr/bin/env python3
    

    As pointed out in the comments, /usr/bin/env python3 makes it easier to work with venvs and other local installations of python.

  3. Invoke the script with

    ./myprogram.py < myinput
    

To handle the input, you will need to import sys in your script, and then read from sys.stdin.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement