shebang not working for python script - python

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?

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

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

Related

Run python program in jenkins job

I am trying to run below code in jenkins job, code is to delete files older than 30 days from a directory in ftp server.
I created freestyle project job in jenkins and in build section I have selected "Execute shell" and I have added below code.
#! /usr/bin/python
import time
import ftputil
host = ftputil.FTPHost('host', 'user', 'pass')
mypath = '/path/directory'
now = time.time()
host.chdir(mypath)
names = host.listdir(host.curdir)
for name in names:
      if host.path.isfile(name):
         host.remove(name)
host.close()
I am facing below error on build
Building remotely on docker-4 (maven linux docker) in workspace /var/lib/jenkins/workspace/Capacity/folder/Test_job
[Test_job] $ /usr/bin/python /tmp/jenkins8422988908580909797.sh
File "/tmp/jenkins8422988908580909797.sh", line 6
SyntaxError: Non-ASCII character '\xc2' in file /tmp/jenkins8422988908580909797.sh on line 6, but no encoding declared;
and I also tried with "Execute python script" build option I am facing similar error like below.
Building remotely on docker-4 (maven linux docker) in workspace /var/lib/jenkins/workspace/Capacity/folder/Test_job
[Test_job] $ python /tmp/jenkins5375363980435767190.py
File "/tmp/jenkins5375363980435767190.py", line 6
SyntaxError: Non-ASCII character '\xc2' in file /tmp/jenkins5375363980435767190.py on line 6, but no encoding declared;
I am new to jenkins job and python, can any one guide how can I resolve this issue.
2) If I select jenkins pipeline job how can I call this python code from jenkinsfile.
Try to install ftputil globally.
pip install ftputil
or
sudo pip install ftputil
The following shell script works with no error, once I installed ftputil globally with sudo.
#!/usr/bin/env python
import time
import datetime
import ftputil
There is nothing special about this python program. If you want to execute it from shell. Then create shell script file e.g. python_prog.sh then, change permissions chmod +x python_prog.sh python_prog.py
python_prog.sh
#!/bin/sh
python python_prog.py
Finally, run the script from terminal . python_prog.sh or ./python_prog.sh

Executable .py file with shebang path to which python gives error, command not found

I have a self-installed python in my user directory in a corporate UNIX SUSE computer (no sudo privilege):
which python
<user>/bin/python/Python-3.6.1/python
I have an executable (chmod 777) sample.py file with this line at the top of the file:
#!<user>/bin/python/Python-3.6.1/python
I can execute the file like this:
python sample.py
But when I run it by itself I get an error:
/full/path/sample.py
/full/path/sample.py: Command not found
I have no idea why it's not working. I'm discombobulated as what might be going wrong since the file is executable, the python path is correct, and the file executes if I put a python command in the front. What am I missing?
EDIT:
I tried putting this on top of the file:
#!/usr/bin/env python
Now, I get this error:
: No such file or directory
I tried this to make sure my env is correct
which env
/usr/bin/env
EDIT2:
Yes, I can run the script fine using the shebang command like this:
<user>/bin/python/Python-3.6.1/python /full/path/sample.py
Your file has DOS line endings (CR+LF). It works if you run python sample.py but doesn't work if you run ./sample.py. Recode the file so it has Unix line endings (pure LF at the end of every line).
Try using #!/usr/bin/env python as described in this post. Let the OS do the work.

How do I make a python script executable?

How can I run a python script with my own command line name like myscript without having to do python myscript.py in the terminal?
Add a shebang line to the top of the script:
#!/usr/bin/env python
Mark the script as executable:
chmod +x myscript.py
Add the dir containing it to your PATH variable. (If you want it to stick, you'll have to do this in .bashrc or .bash_profile in your home dir.)
export PATH=/path/to/script:$PATH
The best way, which is cross-platform, is to create setup.py, define an entry point in it and install with pip.
Say you have the following contents of myscript.py:
def run():
print('Hello world')
Then you add setup.py with the following:
from setuptools import setup
setup(
name='myscript',
version='0.0.1',
entry_points={
'console_scripts': [
'myscript=myscript:run'
]
}
)
Entry point format is terminal_command_name=python_script_name:main_method_name
Finally install with the following command.
pip install -e /path/to/script/folder
-e stands for editable, meaning you'll be able to work on the script and invoke the latest version without need to reinstall
After that you can run myscript from any directory.
I usually do in the script:
#!/usr/bin/python
... code ...
And in terminal:
$: chmod 755 yourfile.py
$: ./yourfile.py
Another related solution which some people may be interested in. One can also directly embed the contents of myscript.py into your .bashrc file on Linux (should also work for MacOS I think)
For example, I have the following function defined in my .bashrc for dumping Python pickles to the terminal, note that the ${1} is the first argument following the function name:
depickle() {
python << EOPYTHON
import pickle
f = open('${1}', 'rb')
while True:
try:
print(pickle.load(f))
except EOFError:
break
EOPYTHON
}
With this in place (and after reloading .bashrc), I can now run depickle a.pickle from any terminal or directory on my computer.
The simplest way that comes to my mind is to use "pyinstaller".
create an environment that contains all the lib you have used in your code.
activate the environment and in the command window write pip install pyinstaller
Use the command window to open the main directory that codes maincode.py is located.
remember to keep the environment active and write pyinstaller maincode.py
Check the folder named "build" and you will find the executable file.
I hope that this solution helps you.
GL
I've struggled for a few days with the problem of not finding the command py -3 or any other related to pylauncher command if script was running by service created using Nssm tool.
But same commands worked when run directly from cmd.
What was the solution? Just to re-run Python installer and at the very end click the option to disable path length limit.
I'll just leave it here, so that anyone can use this answer and find it helpful.

Python encountering unexpected ')` in very short program

Python is seeing some problem with how I am opening a file with the code below
if __name__ == "__main__":
fileName = sys.argv[1]
with open(fileName, 'r') as f:
for line in f:
print line
It is producing the error
./search.py: line 3: syntax error near unexpected token `('
./search.py: line 3: ` with open(fileName, 'r') as f:'
Am I missing an import? What could be the cause of this?
EDIT: OS - CentOS, Python version 2.6.6
Not sure how I installed, I am running an image from a .edu openstack site. Not sure of the distribution, binaries, ...
You must add import sys in order to use sys.argv. Check this out.
I have tried this:
chmod u+x yourfile.py
./yourfile.py
and it gives me:
./jd.py: line 4: syntax error near unexpected token `('
./jd.py: line 4: ` with open(fileName, 'r') as f:'
If you are doing ./search.py file then add at the beginnig of your file #!/usr/bin/env python. Otherwise, use python file.py input
The problem is that you aren't running your program with Python at all! When you do ./script (assuming that script is a text script, and not a binary program), the system will look for a line at the top of the file beginning with the sequence #!. If it finds that line, the rest of the line will be used as the interpreter of that script: the program which runs the script. If it doesn't find that line, the system defaults to /bin/sh.
So, basically, by omitting the magic line #!/usr/bin/python at the top of your script, the system will run your Python script using sh, which will produce all sorts of incorrect results.
The solution, then, is to add the line #!/usr/bin/python (or an equivalent line, like #!/usr/bin/env python) to the top of your Python script so that your system will run it using Python. Alternately, you can also always run your program using python search.py, instead of using ./search.py.
(Note that, on Linux, filename extensions like .py mean almost nothing to the system. Thus, even though it ends with .py, Linux will just execute it as if you wrote /bin/sh search.py).
Either:
the first line of search.py should be a #! comment specifying the path to locate the python executable, usually [#!/usr/bin/env python](Why do people write #!/usr/bin/env python on the first line of a Python script?
on-the-first-line-of-a-python-script). Usually this is #!/usr/env/bin python . Don't use a hardpath e.g. #/opt/local/bin/python2.7
or else you can invoke as python yourfile.py <yourargs> ...
PREVIOUS: If import sys fails, post more of your file please.
Maybe your install is messed up.
Can you import anything else successfully, e.g. import re?
What are your platform, OS and Python version? How did you install? source? binaries? distribution? which ones, from where?

Python: How to include the exe file of a script in setup.py

I am trying to learn Python by myself using Zed A.Shaw's book Learn Python the hard way.
At exercise 46. I'am supposed to create a project skeleton (i.e. create a setup.py file, create modules, and so). Then make a project.
I have to put a script in my bin directory that is runnable for my system. I wrote the simple Hello World! script turned it into an .exe file using cxfreeze.
However when I try to install my setup.py file (i.e. By typing python setup.py install in the cmd), I can't install this .exe file instead I can only install the script script.py
How can I install this exe file.
This is my setup.py file:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'First project',#ex46
'author': 'author',#
'url': '',#N/A
'download_url': '',#N/A
"author_email": "author_email#email.com"
'versio': '3.1',
'install_requires': ['nose'],
'packages': ['skeleton\quiz46','skeleton\\tests'],
'scripts': ['skeleton\\bin\helloscript.py','skeleton\\bin\helloscript.exe'],
'name': 'quiz46'
}
But this gives me the following error:
UnicodeDecodeError
I have also tried putting skeleton\bin\helloscript.exe but that gives me a similiar Error!
My OS is Windows 7, and I am using Python 3.1.
Again what I want is for the setup.py to install my .exe file too not just it's script.
I don't think the script option is meant to handle anything but text files. If you have a look at the source code for distribute (aka setuptools), the write_script command will try to encode('ascii') the contents if it's anything other than a python script AND if you are using Python 3. Your cxfreeze exe is a binary file, not a text file, and is likely causing this to choke.
The easier option to get setuptools to include a executable script in the installation process is to use the entry_points option in your setup.py rather than scripts:
entry_points={'console_scripts':['helloscript = helloscript:main'] }
The console_script will automatically wrap your original helloscript.py script and create an exe (on Windows) and install it into your Python's Script directory. No need to use something like cxfreeze.

Categories