Execute script in Python2 on Unix Command Line - python

Yes, I know I can do
python2 cal.py
What I am asking for is a way to execute it on the command line such as:
calpy
and then the command afterwards. I put in in a path and when I write cal.py in the command line:
/usr/bin/cal.py: line 5: print: command not found
I don't want to issue cal.py to run my script, I want it to be issued with calpy
I'm running Arch Linux if that helps, thanks. Sorry for my English.

In order for bash to know to run your script via the Python interpreter, you need to put an appropriate shebang at the start. For example:
#!/usr/bin/python
tells bash to run /usr/bin/python with your script as the first argument. I personally prefer
#!/usr/bin/env python
which is compatible with virtualenv. You also need to ensure that the permissions on your script allow it to be executed:
~$ chmod +x path/to/cal.py
Finally, in order to call cal rather than path/to/cal.py, you need to remove the .py extension and make sure that the directory containing cal is in your command search path. I prefer to add ~/bin to the search path by modifying the $PATH environment variable in ~/.bashrc:
export PATH=$HOME/bin:$PATH
then put my own executables in ~/bin. You could also copy (or symlink) cal to one of the system-wide binary directories (/bin or /usr/bin), but I consider it bad practice to mess with system-wide directories unnecessarily.

Ok, you need a couple of things for achive what you want.
First you have to tell your script "How" is going to execute/interpret it. You can do this writting
#/usr/bin/env python
at the very beggining of the file.
The problem you have is the system is trying to execute the script using bash. And in bash there is no print command.
Second you need give execution privileges to your script. And of course if you want to call your script through the command "calcpy", the script has to be called like that.

Put this (exactly this) as the first line of your script:
#!/usr/bin/env python

Related

Run python script as one of the command of command line tool

I am new to Python, could someone please let me know if we can register our python script to work as one of the command of cmd.exe, I am not asking about parsing or accepting command line arguements using argparse, etc..
Lets say I have a SearchDir.py file, to run it from cmd prompt I have to do "python SearchDir.py", so is there any way to simply do "SearchDir" and it should act as one of the command of cmd.exe
Yes, it is possible (if I have understood you correctly. The question was a bit unclear)
The first thing you need to do is to add a shebang to the top of your script: https://en.wikipedia.org/wiki/Shebang_(Unix). I see you mentioned cmd.exe so I assume you need this to work on Windows? In that case you should read https://docs.python.org/3/using/windows.html#shebang-lines as well
On unix hosts, the second thing we need to do is set our file as executable with chmod +x <filename>. I try to stay away from Windows, but from what I remember this is not relevant on Windows.
Last you need to place the script in a folder referenced by your $PATH-variable
The script will now be accessible as SearchDir.py from cmd.exe or a unix shell. If you want to omit the ".py"-part you simply rename the file to just "SearchDir"

Running Shell script from within Python issue

So, I am trying to run a Shell script from Python and I double checked that the location of the script.sh is all correct (because when I run it from sublime, the script.sh opens). What I have to call script.sh is:
subprocess.call("script.sh", shell=True)
When I run that, the function returns 0. However, the script is supposed to create a file in my folder and write into it, which it is not doing. It does work when I run the script from cygwin command prompt.
What could be wrong?
Please ensure you have added:
!/bin/bash
as the first line and also make sure that the file script.sh has executable permission.
chmod u+x script.sh
then try specifying the complete path:
subprocess.call("/complete/path/script.sh", shell=True)
At the top of your shell script somewhere, put the line:
pwd >/tmp/mytempfile
and then run the Python script and go look into that file.
This will let you find out the working directory of your scripts which, in the majority of cases where a file doesn't appear to be created, is different to what you think it should be.
You may also want to check the shell script to ensure it's not changing the working directory before creating the file but that would be unlikely given you've stated it works okay from the command line.
If you add the line to create the temporary file and it doesn't actually get created, then your script is not executing.
In that case, you could try a few things. The first is to fully specify the script on the off chance that Python isn't in the correct directory. In other words, something like:
subprocess.call("/actual/path/to/script.sh", shell=True)
Or you could try to run the actual bash executable with the script as an argument:
subprocess.call("bash -c script.sh", shell=True)

How to run a python program in a shell without typing "python"

I am new to python. I wrote a program which can be executed by typing python Filecount.py ${argument} Why I see my teacher can run a program by only typing Filecount.py ${argument}. How to achieve that?
Make it executable
chmod +x Filecount.py
and add a hashbang to the top of Filecount.py which lets the os know that you want to use the python interpreter to execute the file.
#!/usr/bin/env python
Then run it like
./Filecount.py args
in linux-based OSs you must include a line (at the beginning of your script, i.e., the first line) like this:
#!/usr/bin/python
this tells the OS to seek your python interpreter at that location. this applies to any script.
remember to have the permissions in your script file (i.e. executable) for that to work.
Add a shebang line to the top of your file: http://en.wikipedia.org/wiki/Shebang_(Unix)#Purpose
It will tell the system which executable to use in running your program.
For example, add
#!/usr/bin/env python
as the first line, and then change the permissions of the file so you can execute it.
chmod +x Filecount.py
Best of luck!

How to distribute my Python/shell script?

I have written a very simple command line utility for myself. The setup consists of:
A single .py file containing the application/source.
A single executable (chmod +x) shell script which runs the python script.
A line in my .bash_profile which aliases my command like so: alias cmd='. shellscript' (So it runs in the same terminal context.)
So effectively I can type cmd to run it, and everything works great.
My question is, how can I distribute this to others? Obviously I could just write out these instructions with my code and be done with it, but is there a faster way? I've occasionally seen those one-liners that you paste into your console to install something. How would I do that? I seem to recall them involving curl and piping to sh but I can't remember.
Upload your script to something like ideone. Then tell your friend to pipe it into python. Example script:
def print_message():
print "This is my very special script!"
if __name__ == "__main__":
print_message()
Example of running script:
username#server:~$ curl http://ideone.com/plain/O2n3Pg 2>/dev/null | python
This is my very special script!
chmod +x cmd.py
then they can type ./cmd.py
they can also use it piped.
I would add that unix users would probably already know how to make a file executable and run it, so all you'd have to do is make the file available to them.
Do make sure they know what version(s) of python they need to run your script.

Ubuntu Python shebang line not working

Unable to get shebang line working in Ubuntu for python script. I only get a command not found error each time.
test.py
#!/usr/bin/env python
print ('!')
Ran
:which python
/usr/bin/python
Played around with different locations for python in the shebang but no luck including what was provided by which python. Any tips on how to troubleshoot this?
Thanks
If you are trying to run the command as
$ test.py
the error may not have anything to do with the shebang. Rather, the directory that test.py resides in is not in your PATH. Try
$ ./test.py
to bypass PATH lookup.
(This is in addition to making sure that the script itself is executable.)
On the python docs page it says:
To easily use Python scripts on Unix, you need to make them
executable, e.g. with
$ chmod +x script and put an appropriate Shebang line at the top of
the script. A good choice is usually
#!/usr/bin/env python
which searches for the Python interpreter in the whole PATH. However,
some Unices may not have the env command, so you may need to hardcode
/usr/bin/python as the interpreter path.
I don't know if this applies for you or not.
Apart from executing the script with a preceding dot or making it executable, there might be another issue:
If you try to use a script written with a windows editor, it may contain windows line endings. Removing these can make the shebang work again.
To remove such line endings, refer to How to convert Windows end of line in Unix end of line (CR/LF to LF) for instance.
See also my general remarks on failed shebang evaluations at my other answer.
Make sure that the "FIRST LINE" is the shebang.
Do not give any newline character in the beginning of the file.
"No newline character in beginning"
This may be due to a kernel misconfiguration. Take a look at your kernel's config options, and check if CONFIG_BINFMT_SCRIPT is set:
zcat /proc/config.gz | grep CONFIG_BINFMT_SCRIPT
If the output of this command is anything besides CONFIG_BINFMT_SCRIPT=y, this means that your kernel will not allow you to use shebangs. You will need to get a new kernel or recompile your current kernel with CONFIG_BINFMT_SCRIPT=y.
You can also check your line ending in gitbash/pycharm terminal by typing,
cat .gitattributes
this will list the setup, for linux setup paste this
*.sh text eol=lf
if this doesnt work, then better create a new branch and delete the exisiting file and create newfile.
This worked for me

Categories