Let's say I want to use a shell script to run a python file, called test.py, which is in a directory called Test in my home directory. I tried the following code, which does not work:
#!/bin/bash
echo "Starting."
module load gcc/4.8.2
module load python/3.4.1
echo "Modules loaded."
$HOME/Test/test.py
exit 0
I do not believe that how I am trying to run the program ($HOME/Test/test.py) works. I have not been able to determine how to do this, despite searching for a long time. Any help would be appreciated.
This is likely one of the following, or it may be a combination of both.
The python script is not executable. Fix with:
chmod u+x $HOME/Test/test.py
The script does not start with a #! line pointing to python. Fix that by making this the first line of test.py:
#!/usr/bin/env python
You can also use a full path instead of using /usr/bin/env to use $PATH to resolve the name.
#!/usr/local/bin/python
Related
Why can't we open the .py file with its path by python?
noob asking. Apologies if I am stupid.
You don't.
If you have the file /home/user/scripts/tests/main.py, with the following content:
print("Hello World")
Running python3 /home/user/scripts/tests/main.py will run the python script as expected.
There may be an issue with your PATH or with how you're entering the path to the file
You probably use similar construction:
myscript.py
It means, that terminal consider your input as a command, and tries to find in in $PATH.
Firstly you need to use absolute or relative addressation:
./myscript.py
# or
/path/to/file/myscript.py
Secondly, you need to make sure, your script has an executable bit:
chmod +x myscript.py
Thirdly, make sure you use shebang in the first line of your scriptb:
#!/usr/bin/python
Shebang explains to your shell, which app should process the file.
Otherwise you'll need to run it via python directly:
python myscript.py
Question: In command line, how do I call a python script without having to type python in front of the script's name? Is this even possible?
Info:
I wrote a handy script for accessing sqlite databases from command line, but I kind of don't like having to type "python SQLsap args" and would rather just type "SQLsap args". I don't know if this is even possible, but it would be good to know if it is. For more than just this program.
You can prepend a shebang on the first line of the script:
#!/usr/bin/env python
This will tell your current shell which command to feed the script into.
You want a shebang. #!/path/to/python. Put that on the first line of your python script. The #! is actually a magic number that tells the operating system to interpret the file as a script for the program named. You can supply /usr/bin/python or, to be more portable, /usr/bin/env python which calls the /usr/bin/env program and tells it you want the system's installed Python interpreter.
You'll also have to put your script in your path, unless you're okay with typing ./SQLsap args.
Assuming this is on a unix system, you can add a "shebang" on the top of the file like this:
#!/usr/bin/env python
And then set the executable flag like this:
chmod +x SQLsap
Another way to do this would be to package your python script.
Then all you would have to do is run $ pip install package-name and simply running $ package-name from any directory would execute your python script.
I would recommend this method since it enables you to quickly share/install/use/remove your python script.
I wrote a simple script QuickPackage that can instantly create and upload python package for your awesome script by just entering the path of your python script.
Example:
$ pip install quickpackage
Usage :
Usage
Simply run quickpackage and enter the path of your python script.
Example:
❯ quickpackage
Enter name: quickpackage
Enter version: 1.1
Enter description: Instantly create and upload python package for your script
Enter github url: https://github.com/yask123/quick-package
enter author: Yask Srivastava
Enter email: yask123#gmail.com
Path of python script file: run.py
running register
....
running upload
Submitting dist/quickpackage-1.1.tar.gz to https://pypi.python.org/pypi
Server response (200): OK
Now simply execute your script by running$ quickpackage (In this case)
On Windows or DOS you can come close by putting your python code into a .BAT file like this.
rem = ''' this line interpreted by BAT and PYTHON
#REM BAT-ONLY code begins now inside PYTHON comment
#echo off
python "%~dpnx0" %*
goto :eof
#REM CMD-ONLY code ends
'''
import sys
print sys.path
Unfortunately, I can't get rid of the first line message on the output, but you could always change the text after ''' to be something like the application's name and people wouldn't notice.
Ideally, you wouldn't put lots of Python code in the .BAT file but would import a .py file and then run its .__main__ method.
In unix, you use a shebang line at the start of your script:
#!/usr/bin/env python
make the file executable:
chmod +x arbitraryname
and put it in a directory on your PATH (can be a symlink):
cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname
In windows, files like *.py has been set to be open with python.exe by default. (If not, you can set manually.) So you can run *.py files in console directly.
Note that:
In windows, text new line code is "\r\n", but in unix, it is "\n". If your python script is windows format, then executing in unix will report "No such file or directory" error.
To repair this problem, just replace all "\r\n" with "\n" in unix will be ok.
How can I create functions and software for my Linux server? Let me explain this in a bit more detail.
So for my Linux server which I access with my SSH client, I have made a few Python scripts that work fine, but what I really want to do is have these Python scripts active all the time, such that I can execute functions I've created in the script (such as "def time(): ...") just by typing "time" in to the command line rather than starting up a script with ./script-name.py and then type "time". Do I need to install my Python files in to the system in some way?
I struggled searching Google because I didn't fully understand what to search, and results that came up weren't really related to my request. I did find the cmd Python module and learned how to create cmd interpreters, however, in order for me to access the commands I defined in the cmd interpreter, I had to first start the script, which as I explained above, not what I am looking for.
How can I make script-level Python functions callable from the Linux command line?
If you're using Python, you'll still need to fire up the interpreter, but you can make that happen automatically.
Start by making your script executable. Run this command in the shell:
chmod +x script-name.py
ls -l script-name.py
The output of ls should look something like this (note the xs in the left-hand column):
-rwxr-xr-x 1 me me 4 Jan 14 11:02 script-name.py
Now add an interpreter directive line at the top of your script file - this tells the shell to run Python to interpret your script:
#!/usr/bin/python
Then add code at the end of the file that calls your function:
if __name__ == '__main__':
time()
The if statement checks to see if this is the file that is being executed. It means you can still import your module from another Python file without the time() function being automatically called, if you want.
Finally, you need to put your script in the executable path.
mkdir -p $HOME/bin
mv script-name.py $HOME/bin/
export PATH=$HOME/bin:$PATH
Now you should be able to run script-name.py, and you'll see the output of the time() function. You can rename your file to whatever you like; you can even remove the .py extension.
Additional things you can do:
Use the argparse module to add command line arguments, e.g. so you can run script-name.py time to execute the time() function
Put the script in a system-wide path, like /usr/local/bin, or
Add the export PATH=$HOME/bin:$PATH line to your .bashrc so that it happens by default when you log in
The answer above is by far more complete and more informative than mine. I just wanted to offer a quick and dirty alternative.
echo "alias time='<your script> time'" > ~/.bashrc
bash
Like I said, quick and dirty.
I'm trying to change the terminal directory through a python script. I've seen this post and others like it so I know about os.chdir, but it's not working the way I'd like. os.chdir appears to change the directory, but only for the python script. For instance I have this code.
#! /usr/bin/env python
import os
os.chdir("/home/chekid/work2/")
print os.getcwd()
Unfortunately after running I'm still in the directory of the python script (e.g. /home/chekid) rather than the directory I want to be in. See below.
gandalf(pts/42):~> pwd
/home/chekid
gandalf(pts/42):~> ./changedirectory.py
/home/chekid/work2
gandalf(pts/42):~> pwd
/home/chekid
Any thoughts on what I should do?
Edit: Looks like what I'm trying to do doesn't exist in 'normal' python. I did find a work around, although it doesn't look so elegant to me.
cd `./changedirectory.py`
You can't. The shell's current directory belongs to the shell, not to you.
(OK, you could ptrace(2) the shell and make it call chdir(2), but that's probably not a great design, won't work on Windows, and I would not begin to know how to do it in pure Python except that you'd probably have to mess around with ctypes or something similar.)
You could launch a subshell with your current working directory. That might be close enough to what you need:
os.chdir('/path/to/somewhere')
shell = os.environ.get('SHELL', '/bin/sh')
os.execl(shell, shell)
# execl() does not return; it replaces the Python process with a new shell process
The original shell will still be there, so make sure you don't leave it hanging around. If you initially call Python with the exec builtin (e.g. exec python /path/to/script.py), then the original shell will be replaced with the Python process and you won't have to worry about this. But if Python exits without launching the shell, you'll be left with no shell open at all.
You can if you cheat: Make a bash script that calls your python script. The python script returns the path you want to change directory to. Then the bash script does the acctual chdir. Of course you would have to run the bash script in your bash shell using "source".
The current working directory is an attribute of a process. It cannot be changed by another program, such as changing the current working directory in your shell by running a separate Python program. This is why cd is always a shell built-in command.
You can make your python print the directory you want to move to, and then call your script with cd "$(./python-script.py)". In condition your script actually does not print anything else.
I've a shell script with two shebangs, the first one tells #!/bin/sh and after a few lines the other one is #!/usr/bin/env python.
When this script is given executable permission and ran as ./script.sh, the script works fine, uses /bin/sh in first part and uses python interpreter in latter part.
But when the script is run as sh script.sh, the second shebang is not recognized and the script fails. Is there anyway I can force to change the interpreter if the script is run explicitly as sh script.sh.
The reason I need this is because I need to run the scripts through a tool which runs as sh script.sh
As far as I know you cannot have two shebang lines in one script. The shebang works only when -
it is on the first line
it starts in column one
If you need to run python code then have it in another script and then call the script by doing
python path/to/the/script.py
A better way to do this would be to use a shell here document. Something like this:
#!/bin/sh
curdir=`pwd`
/usr/bin/env python <<EOF
import os
print os.listdir("$curdir")
EOF
This way, you won't need to distribute the code on two separate files.
As you see, you can even access shell variables from the python code.
have your script.sh script invoke the python interpreter directly:
#!/bin/sh
# include full path if needed
python (your python interpreter arguments)