简体   繁体   English

从shell运行Python脚本时出错

[英]Error running Python script from shell

I am trying to pipe output from a command written in the terminal to a Python script. 我正在尝试将终端中编写的命令的输出通过管道传递给Python脚本。

For example: 例如:

ls | ./foo.py

I wrote a Python script to do the same: 我写了一个Python脚本来做同样的事情:

#foo.py
import fileinput

with fileinput.input() as f_input : 
    for line in f_input : 
        print(line,end='')

But this does not seem to work, when I run the following command: 但这在我运行以下命令时似乎不起作用:

$ ls | sudo ./foo.py

I get an error that says: 我收到一条错误消息:

$ ./foo.py: command not found

I have checked the working directory and I can see the foo.py when I use the ls command, so what am I doing wrong here? 我已经检查了工作目录,使用ls命令时可以看到foo.py ,那么我在做什么错呢?

You have to pipe it to the Python executable, not to the name of a file. 您必须将其通过管道传递到Python可执行文件,而不是文件名。 As the error says, that filename doesn't represent a command it knows. 如错误所示,该文件名并不表示它知道的命令。

ls | py ./foo.py

Use py or python or however you run the Python interpreter on your particular system. 使用pypython或者在特定系统上运行Python解释器。

It seems like you forgot the Shebang : 好像您忘记了Shebang

#!/usr/bin/env python3
import fileinput

with fileinput.input() as f_input :
    for line in f_input :
        print(line,end='')

Also remember make it as executable via command: 还记得通过命令将其设置为可执行文件:

chmod +x foo.py

Then run your command again. 然后再次运行您的命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM