Why can't the import command be found?

不打扰是莪最后的温柔 提交于 2020-01-13 08:17:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27563854/why-cant-the-import-command-be-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!