Python 为什么找不到导入命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27563854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:57:28  来源:igfitidea点击:

Why can't the import command be found?

pythonshebang

提问by styvane

I am using the inputfunction from fileinputmodule to accept script via pipesor input fileHere is the minimum script:

我正在使用模块中的input函数fileinput通过pipesinput file这里是最小脚本来接受脚本:

finput.py

输入文件

import fileinput

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

After making this script executable, I run ls | ./finput.pyand get unexpected error message

使这个脚本可执行后,我运行ls | ./finput.py并得到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/python3before the import statement.

我发现的唯一解决方法是在#!/usr/bin/env/python3导入语句之前添加。

But this issue seems to be related only to the fileinputmodule. Since the following script worked well without a shebang:

但这个问题似乎只与fileinput模块有关。由于以下脚本在没有 的情况下运行良好shebang

fruit.py

水果.py

import random

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

Now what am I missing? Why can't the importcommand be found since the shebangis not requiredin finput.py?

现在我错过了什么?为什么不能import,因为该命令可以找到shebang不是必需finput.py

采纳答案by Thomas Orozco

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

你需要告诉你的操作系统这是一个 Python 程序,否则,它被解释为一个 shell 脚本(import找不到命令)。

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

正如您所确定的,这是通过使用 shebang 行来完成的:

#!/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).

仅当您要像这样运行脚本时才需要:./script.py,它告诉您的操作系统“运行此可执行文件”。这样做需要您的操作系统确定它应该如何运行程序,并且它依赖于 shebang 行(除其他外)。

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.

但是,如果您运行python script.py(我猜您是为fruit.py)运行的,那么 Python 不会询问您的操作系统是否是 Python 程序,因此 shebang 行无关紧要。