I want to run a python script without explicitly having to call "python" every time in my shell. I've tried to add the shebang #!/path/to/python but this does not seem to work. Does anyone know a work around this? Many thanks.
You've got to add the shebang:
#!/usr/bin/env python
Then make the script executable:
chmod +x foo
Then you can run it like any other executable:
./foo
And a note from Homer6: if you're editing the file from windows and invoking it on linux, you may run into the cryptic "No such file or directory" error. It's due to the line endings of the lines being CRLF instead of LF. If you convert them to LF, the script will execute as expected. Notepad++ > View > Show Symbols > Show End of Line to show the EOL characters. And Notepad++ > Edit > EOL Conversion > Unix Format to convert all line endings to use LF. Alternatively, you can use the dos2unix tool (dos2unix foo.py), which is present on most Linux systems.
It didn't really apply to your personal scripts but as you are quoting beets, note that it is also possible to automate this action when you are distributing your packages, thanks to setuptools entry_point option.
So if you are distributing a package like myModule and want to make the main_function() function accessible via typing mymodulescript in the console you would probably add something like this to your setup.py file :
setup(
# your other arguments ..
entry_points={
'console_scripts': [
'mymodulescript = myModule:main_function'
]
}
)
Add a line at the top of your script:
#! /usr/bin/env python
Rename your script from script_name.py to script_name
make the script executable: chmod +x script_name
The line at the top selects the same python that you get when typing python at the prompt. You can also specify a direct path:
#!/opt/python/3.6/bin/python
Another workaround could be to use an alias defined in the .bashrc :
e.g. add the following line in your .bachrc file :
alias mypythonalias="python mypyrhonfile.py"
type in terminal :
source ~/.bashrc
and then you may simply type:
mypythonalias
to execute the python file.
Ensure you are able to run /path/to/python on your terminal. And make sure you have given execute permission for your python file. You can give permission for the file by
chmod +x mypythonfile.py
Related
dag#Arokh:~$ source /home/dag/.bashrc
dag#Arokh:~$ echo $PATH
/home/dag/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
dag#Arokh:~$ python3 /home/dag/.local/bin/facemorpher --version
Face Morpher 1.0
dag#Arokh:~$ python3 facemorpher --version
python3: can't open file 'facemorpher': [Errno 2] No such file or directory
Adding the directory to PATH doesn't seem to help. How can I make python3 facemorpher work from any directory?
python3 pays no attention to the PATH variable when looking for scripts. This variable controls where the shell looks for executables.
So what should work now, provided the script has executable permissions and a valid shebang like #!/usr/bin/env python3 as its very first line, is that simply
facemorpher
without python3 in front should run the script. Perhaps this is actually what you want and need.
The python3 command without any options expects a file name parameter; there is no simple way to make it look for a file which doesn't exist in the specified directory (which is the current working directory if the filename doesn't have an explicit directory part; this is how the operating system resolves relative file names, and should probably not be messed with for an individual command). For further details about this, perhaps see also Difference between ./ and ~/
For the record, chmod a+x path/to/scriptname adds execute permission to the script for all users on the system, and the path in the shebang after #! should point to your Python interpreter's full path, or the full path to a utility like env which finds it on your PATH and executes it based on just the command name (here, python3; but on some systems, the Python interpreter executable's file name is just python, or more broadly whatever the system's owner decided to name it).
I have a bash script which changes the path on my command line,
This one,
#!/usr/bin/env python
cd /mnt/vvc/username/deployment/
I have a python script which i wish to run after the path changes to the desired path,
The script,
#!/usr/bin/env python
import subprocess
import os
subprocess.call(['/home/username/new_file.sh'])
for folder in os.listdir(''):
print ('deploy_predict'+' '+folder)
I get this
File "/home/username/new_file.sh", line 2
cd /mnt/vvc/username/deployment/
^
SyntaxError: invalid syntax
Any suggestions on how can i fix this?thanks in advance
You need to explicitly tell subprocess which shell to run the sh file with. Probably one of the following:
subprocess.call(['sh', '/home/username/new_file.sh'])
subprocess.call(['bash', '/home/username/new_file.sh'])
However, this will not change the python program's working directory as the command is run in a separate context.
You want to do this to change the python program's working directory as it runs:
os.chdir('/mnt/vvc/username/deployment/')
But that's not really great practice. Probably better to just pass the path into os.listdir, and not change working directories:
os.listdir('/mnt/vvc/username/deployment/')
I have a folder of .py files written in Python 2.7 that I want to convert to Python 3 using the 2to3 tool. Using windows 10 in the cmd prompt i can convert a single file with the following command:
C:\Users\t\Desktop\search>python.exe 2to3.py -w graphicsDisplay.py
however this line is not syntactically correct when in python shell and ideally I'd like to be able to iterate through the whole folder and update all .py files using the by using the following python code in cmd:
C:\Users\t\Desktop\search>python
>>> import os
>>> for files in os.listdir('*filepath*'):
>>> if '.py' == str(files[-3:]):
>>> *...some line of code here to perform 2to3*
its the last line which I can't seem to get right so I guess my question is, how can I call the 2to3 function in python on each iteration of the files variable?
You can do it directly from command line
for %a in (*.py) do python.exe 2to3.py -w "%a"
For each file in the indicated set execute the conversion passing the for replaceable parameter (%a in this sample) that holds the reference to the file being iterated.
Looks like 2to3 support recursive folder checking if you leave out an explicit script to convert.
Would it be easier to have all your scripts in one folder and execute against that instead?
from: https://docs.python.org/2/library/2to3.html#
2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode
I'm on Mac OS 10.6 Snow Leopard and I'm trying to add a directory to my PATH variable so I can run a tiny script I wrote by just typing: python alarm.py at the terminal prompt.
I put the path in my .profile file and it seems to show up when I echo $PATH, but python still can't find script the that I've put in that directory.
Here's the contents of my .profile file in my home directory:
~ toby$ vim .profile
export PATH=/Users/tobylieven/Documents/my_scripts:$PATH
Here's the output of echo $PATH, where all seems well:
~ toby$ echo $PATH
/Users/tobylieven/Documents/my_scripts:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
Here's the script I'm trying to run:
~ toby$ ls /Users/tobylieven/Documents/my_scripts
-rwxrwxrwx# 1 tobylieven staff 276 17 Jan 21:17 alarm.py
Here's the command I'm trying to use to run the script and the fail message I'm getting instead:
~ toby$ python alarm.py
python: can't open file 'alarm.py': [Errno 2] No such file or directory
If anyone has an idea what I might be doing wrong, that'd be great.
Thanks a lot.
PATH is only for executables, not for python scripts. Add the following to the beginning of your Python script:
#!/usr/bin/env python
and run
sudo chmod a+x /Users/tobylieven/Documents/my_scripts/alarm.py
Then, you can type just alarm.py to execute your program.
Which python are you targeting?
Did you install it with brew? It uses a different path.
which python3 or which python
Choose the one you want
Copy that output
Paste it at the top of your python file
add a #! in front of that path so it looks something like
#!/usr/local/bin/python3
Make sure to change the file permissions
chmod +x filename
Put that file in a folder that is in your path
Not sure if your folder is in your path?
echo $path
How to add that folder to your path?
Find your path first
echo $HOME
If you are using bash or zsh you might have something like this
In ~/.bash_profile or ~/.bashrc or ~/.zshrc at the bottom of your file
export PYTHON_UTILS="$HOME/code/python/utils"
export PATH="$PYTHON_UTILS:$PATH"
Consider removing the .py from your file bc it is not needed in this case
Close and open your terminal, which is sourcing your file by its path
And now you should be able to treat your python file similar to a bash command
You don't need to use python3 filename.py to run the file, you can just use filename
From anywhere on your filesystem!
change alarm.py to include:
#!/bin/python
as the very first line in the file.
(or /usr/bin/python, depending on where you python interpreter is located. You can figure this out by typing: which python in the terminal.)
You can then just run alarm.py instead of python alarm.py.
e.g.:
~ toby$ alarm.py
And phihag who beat me by a few seconds is right, you need to add execute permissions (via chmod) to alarm.py.
You need to modify the Python specific path variable: PYTHONPATH.
So:
export PYTHONPATH=/Users/tobylieven/Documents/my_scripts
should get you working.
See: Python Module Search path
Something of interest that I really struggled with on OS X coming from Window, is that you its very hard to get the directory of your current script.
I found this.
#! /bin/zsh
cd "${0:h}"
Now you could execute a python file relative to the executed script instead of having to know the exact path where your python file is.
This might or might not help but I use this a lot to make my scripts and .command files work better.
Am trying to run the following python program
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
f=open('out.txt')
for a in f:
print regex.findall(a)
print '\n'
when I type the code into the interpreter manually, it works as expected
but when i save it as a file and try to run it , it gives errors.
The command i used to run it is
chmod +x
sudo ./pymod.py
ERROR:
./pymod.py: 2: Syntax error: "(" unexpected
if i dont use sudo, the error i get is
./pymod.py: line 2: syntax error near unexpected token `('
./pymod.py: line 2: `regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")'
am using ubuntu 10.04 with everything on default
it takes about 10-15 seconds for the error to appear
Your file should start with shebang. You should include the path to the python interpreter
#!/usr/bin/env python
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
Check out : http://en.wikipedia.org/wiki/Shebang_(Unix)
This is probably executing as a bash script instead of in Python. Put
#!/usr/bin/env python
at the beginning of your script.
When you set something as executable, you have to specify what you want it to run it with, or Linux will consider it to be a bash script.
Add this as the first line of the file:
#!/usr/bin/python
Or run it like:
python pymod.py
Cheers!
Either use the "shebang". I.e. put
#! /usr/bin/python
as the first line of your script.
Or teach your ubuntu how to treat python scripts without it
as described here: http://www.daniweb.com/code/snippet241988.html