import: command not found

Question:

I try to open .py file with MINGW64.
File 1: myname.py

# myname.py
def get_name():
    return "Jim"

File 2: hello.py:

# hello.py
import myname

name = myname.get_name()
print("hello {}".format(name))

When I try to execute hello.py in MINGW64 shell, this error happens:

b2b@DESKTOP-5QEK604 MINGW64 ~/Desktop/Python moje projekty/Dev/apiarena_django/git (master)
$ ./hello.py
./hello.py: line 2: import: command not found
./hello.py: line 4: syntax error near unexpected token `('
./hello.py: line 4: `name = m.get_name()'

how to fix it? I can’t find what’s wrong.

enter image description here

Asked By: Paweł Pedryc

||

Answers:

To run a Python script as a command, without using the "python" command, your first line has to tell the system what interpreter to use. This is called a "she-bang" line. You can either type "python hello.py" or replace the first line with:

#! /usr/bin/env python

As it is, the system is trying to run your command as a bash script. There is no "import" command in bash.

Answered By: Tim Roberts

I think the answer was covered by Tim Roberts implicitly, but to be more explicit, it is just context switching from shell scripting to python; a mistake I have made and thus stumbled across this. Normally run a python file with the python command … unless you really were trying to run a shell script that had python code.

./myPyFile.py

–> needs env set at top of file with:

#! /usr/bin/env python

versus:

> python myPyFile.py
Answered By: Douglas Larson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.