Why can't the import command be found?

I use the input function from the fileinput module to accept a script through pipes or input file Here is a minimal script:

finput.py

 import fileinput with fileinput.input() as f: for line in f: print(line) 

After executing this script executable, I run ls | ./finput.py ls | ./finput.py and getting unexpected error message

 ./finput.py: line 1: import: command not found ./finput.py: line 3: syntax error near unexpected token `(' ./finput.py: line 3: `with fileinput.input() as f:' 

The only fix I found is when I add #!/usr/bin/env/python3 before the import statement.

But this problem seems to be related only to the fileinput module. Since the script worked without shebang :

fruit.py

 import random fruits = ["mango", "ananas", "apple"] print(random.choice(fruits)) 

Now what am I missing? Why can't the import command be found since shebang not required in finput.py ?

+7
python shebang
source share
1 answer

Your need to tell your OS that it is a Python program, otherwise it is interpreted as a shell script (where the import command cannot be found).

As you have determined, this is done using the shebang line:

 #!/usr/bin/env python3 

This is only necessary if you intend to run the script as follows: ./script.py , which says that your OS "runs this executable." This requires your OS to determine how it should run the program, and it relies on the shebang line for this (among other things).

However, if you run python script.py (which I assume you did for fruit.py ), then Python does not ask your OS whether it is a Python program or not, so the shebang line does not matter.

+22
source share

All Articles