If you are trying to execute a .py Python file in the terminal and you get the error "line 1: import: command not found" then the most common reason for it is that you are trying to execute the Python file as a script and it does not have the shebang line.
Example Code:import sys
import subprocess
output = subprocess.check_output(["ls"])
print(output.decode())
Error:
Code2care@Mac % ./sample.py
./sample.py: line 1: import: command not found
./sample.py: line 2: import: command not found
./sample.py: line 4: syntax error near unexpected token `('
./sample.py: line 4: `output = subprocess.check_output(["ls"])'

Fix: import: command not found
There are two ways to look at this issue,
Run the file as a Python Program
In most cases, one might be trying to run the .py file not as a script but as a Python program, so use python command instead of running it as a script.
Example:
python3 script.py
sample.py
data_folder
In most cases, one might be trying to run the .py file not as a script but as a Python program, so use python command instead of running it as a script.
Example:python3 script.py
sample.py
data_folderRun the file as a Python Script
If you want to run the file as a Python Script, then make sure that the first line of your .py file is a shebang,
#!/usr/bin/env python3
import sys
import subprocess
output = subprocess.check_output(["ls"])
print(output.decode())
./sample.py
sample.py
data_folder
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
If you want to run the file as a Python Script, then make sure that the first line of your .py file is a shebang,
#!/usr/bin/env python3
import sys
import subprocess
output = subprocess.check_output(["ls"])
print(output.decode())./sample.py
sample.py
data_folderProvide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!