Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the import command be found?

Tags:

python

shebang

I am using the input function from fileinput module to accept script via pipes or input file Here is the minimum script:

finput.py

import fileinput

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

After making this script executable, I run ls | ./finput.py and get 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 issue seems to be related only to the fileinput module. Since the following script worked well without a 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 the shebang is not required in finput.py?

like image 938
styvane Avatar asked Dec 19 '14 10:12

styvane


People also ask

How do you fix import is not recognized as an internal or external command?

The most efficient way to fix the “is not recognized as an internal command” error is to edit your environment variable and add the appropriate file path there. This is because the Command Prompt utility looks at those paths when you enter a command, and then opens the file if it finds it in one of those directories.

How do you import a command in Python?

The Python import statement imports code from one module into another program. You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist.

What is import command?

Inserts data from an external file with a supported file format into a table, hierarchy, view or nickname. LOAD is a faster alternative, but the load utility does not support loading data at the hierarchy level. Quick link to File type modifiers for the import utility.


1 Answers

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

Like you identified, this is done by using a shebang line:

#!/usr/bin/env python3

This is only needed if you are going to run your script like this: ./script.py, which tells your OS "run this executable". Doing so requires that your OS identify how it's supposed to run the program, and it relies on the shebang line for that (among other things).

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

like image 175
Thomas Orozco Avatar answered Sep 19 '22 13:09

Thomas Orozco