2

I have this code in myname.py:

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

and this in hello.py:

# hello.py
import myname

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

When I try to execute hello.py in the 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 do I fix the problem?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Paweł Pedryc
  • 368
  • 2
  • 5
  • 19

2 Answers2

5

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Thank you for your answer! I've tried earlier ` $ ./hello.py python3 ` and ` $ ./hello.py python`. I thought that I indeed tried to run it via python - for some reason, some people suggested that the "python" statement should be after the directory path. Do you have any idea why they thought so? Is it different on Mac? – Paweł Pedryc Jan 23 '22 at 20:13
  • 1
    No, it's identical on macOS. The `#!` convention is widespread these days but the convention is even older, dating back to the 1960s if not before. – torek Jan 23 '22 at 22:39
  • wow, so it's even stranger that someone suggested that way. I will try to find those threads with these old school answers and ask why it was posted. – Paweł Pedryc Jan 24 '22 at 01:50
  • more about "she-bang" here: https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script – Paweł Pedryc Jan 24 '22 at 04:09
0

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