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
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With