Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shebang not working for python script

Tags:

I've been looking over many answers here on stackoverflow. I've tried absolutely everything. I have this at the top of my AddressConversion.py python script.

#!/usr/bin/env python
import argparse

The objective is to run this as a command utility, meaning I could type

AddressConversion [options][address]

As of now I would settle for being able to type

./AddressConversion [options][address]

I have done the chmod so the file is executable I've ran dos2unix on the file to eliminate any random windows characters(which wouldn't seem possible because the file has only been used on Ubuntu.

I've checked the python install with which python with the results

/usr/bin/python

I've also checked which env and get a similar path The script will work fine when I use the traditional python command. It also works fine when I type:

usr/bin/env python

It will open up the python interpreter. These steps seem to be the solutions suggested anytime someone asks this question. I am getting this error:

./AddressConversion.py: line 1: import: command not found
./AddressConversion.py: line 3: syntax error near unexpected token `('
./AddressConversion.py: line 3: `def init_parser():'

which seems like it is trying to run it as a shell script or something. Any suggestions?

like image 972
SlipFist Avatar asked Apr 10 '18 07:04

SlipFist


2 Answers

created one file executeme.py

#!/usr/bin/env python
print("hello")

make it as executable (optional)

chmod a+x executeme.py

reanme the file

mv executeme.py executeme

Execute now

./executeme

OUTPUT

hello

Another option to create one setup.py file, for more you can read here in entry_points a key name console_script in which you can give the name of executor and target module in format 'name=target'

from setuptools import setup, find_packages
setup(
    name='executor',
    packages=find_packages(),
    install_requires=[,
    ],
    entry_points = {
              'console_scripts': [
                  'executeme=executeme:main',
              ],
          },
)

then run the command

pip install -e /path/to/setup.py

Installing from local src in Development Mode, i.e. in such a way that the project appears to be installed, but yet is still editable from the src tree.

pipdoc

like image 151
Roushan Avatar answered Sep 28 '22 06:09

Roushan


I had a similar issue and it ended being because of the CRLF at the end of lines. These were added when the script was created on a windows machine. To check if this is the case use the file command.

file script.py

It will give you an output like this. "Python script, ASCII text executable, with CRLF line terminators"

To remove the CRLF line terminators do the following.

dos2unix script.py
like image 37
Paradom Avatar answered Sep 28 '22 06:09

Paradom