简体   繁体   中英

Error running Python script from shell

I am trying to pipe output from a command written in the terminal to a Python script.

For example:

ls | ./foo.py

I wrote a Python script to do the same:

#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?

You have to pipe it to the Python executable, not to the name of a file. 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.

It seems like you forgot the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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