How to modify the command to call Python - python

On my Mac, python will run Python 2 and python3 will run Python 3 in the terminal. How can I modify the command so I can call Python 3 with just py?

Add a new file in your home directory called .profile. In there, add a line:
alias py=python3
You'll have to start a new terminal session for this to have any effect.

Place you in the directory where the python3 executable is (with cd command).
Then, enter :
ln -s python3 py
This creates a symbolic link.

Related

Executing python module with Click command using command line

I have created a directory 'prince' which consists of a subdirectory 'src' containing 'main.py' file in it. This main.py uses Click command for input from user using command line. So currently I have to set current working directory to 'prince' in terminal and then execute my module using the command
'$ python -m src.main run --s 10 20 30'
where 'run', '--s' are my click command inputs.
Is there an easy way to wrap 'python -m src.main' to something short to execute my module along with inputs using click command ? Or any better way to execute my module along with inputs from user ?
I hope this will answer your question.
In your src/main.py file you could add a #!/usr/bin/env python3 shebang which means that your program is run by python by default.
And you should give it execute permissions via
chmod +x src/main.py
That means you can now run
src/main run --s 10 20 30
Instead of
$ python -m src.main run --s 10 20 30
Antother way to achieve this would be:
Create a file in the "prince" directory named "start" with Content:
python3 -m src.main "$#"
Give it executable permissions:
chmod +x start
Now you can run:
./start run --s 10 20 30

How to get the command python filename.py to work?

python hello.py in cygdrive isn't working
I've tried this code and it worked: "$ /cygdrive/C/Users/pauls/AppData/Local/Programs/Python/Python37/python.exe hello.py"
I want to compile a python file in cygdrive by calling it like python
go into you home directory cd ~ and open up your .bashrc file to add an alias
alias python="/cygdrive/C/Users/pauls/AppData/Local/Programs/Python/Python37/python.exe"

Execute a python script as a command

I'm writing a python script which will be placed in a location. I want to execute it just like a command. for ex.
$ find_branch test
where find_branch is a script placed in anywhere in the system.
I would like to know how to achieve this. I can run it on the place where the script is present by chmod u+x on the script and removing the .py from the script
sudo nano /usr/bin/testpyscript
Then inside the script:
#!/usr/bin/python
print("I'm a python script")
Give it x permission:
sudo chmod +x /usr/bin/testpyscript
Now you can use it as a regular command:
bash-4.2$ testpyscript
I'm a python script
It doesn't have to be exactly at /usr/bin, any location that is inside your $PATH will do. Let's say you want it to be located at some folder inside your home directory, you could do something like this:
pwd
/home/brunorb
mkdir somedir
sudo mv /usr/bin/testpyscript somedir/
export PATH=$PATH:/home/brunorb/somedir/
testpyscript # from any folder in the system
I'm a python script
Make sure python has been added to your path and #!/usr/bin/python is located at the top of your script.
Note You could just try adding your script to your /usr/local/bin/ directory and give it the proper permissions.
sudo cp <your script> /usr/local/bin/
You have a number of options on how to achieve this.
Add the location where you put the script to your PATH environment variable, for example in your ~/.bashrc script:
export PATH="${PATH}:/folder/where/you/put/the/script"
Install the script to a location that is already on your path. It does not have to be a system folder like /usr/bin. Many default Bash setups will include ~/bin in your PATH.
Give the full path to your script on the command line:
/folder/where/you/put/the/script/find_branch test
Run the script through Python. This is very similar to option #2:
python /folder/where/you/put/the/script/find_branch test
Create an alias for the script in your environment. In bash you would do something like the following in your ~/.bashrc:
alias find_branch='/folder/where/you/put/the/script/find_branch'
OR
alias find_branch='python /folder/where/you/put/the/script/find_branch'
For options #1, #2, #3 and #5a to work properly, you should have a shebang with the version of python as the first line of the script. Any of the following will do, depending on how you have/want your environment set up:
#!/usr/bin/python
#!/usr/bin/python2
#!/usr/bin/python3
#!/usr/bin/env python
#!/usr/bin/env python2
#!/usr/bin/env python3
Finally, you do not have to remove the .py extension from the script if you do not want to. Many bash scripts have a .sh extension, for example, which does not prevent them from running as-is. You just have to include the extension in the name of the script when you run it.

Shell : workon not found [duplicate]

So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the mkvirtualenv function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries.
I am trying to add a bin/run-app executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in
#!/bin/bash
# cd into the project directory
workon "$(cat .venv)"
python main.py
A file .venv contains the virtualenv name. But when I run this script, I get workon: command not found error.
Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script.
So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
Just source the virtualenvwrapper.sh script in your script to import the virtualenvwrapper's functions. You should then be able to use the workon function in your script.
And maybe better, you could create a shell script (you could name it venv-run.sh for example) to run any Python script into a given virtualenv, and place it in /usr/bin, /usr/local/bin, or any directory which is in your PATH.
Such a script could look like this:
#!/bin/sh
# if virtualenvwrapper.sh is in your PATH (i.e. installed with pip)
source `which virtualenvwrapper.sh`
#source /path/to/virtualenvwrapper.sh # if it's not in your PATH
workon $1
python $2
deactivate
And could be used simply like venv-run.sh my_virtualenv /path/to/script.py
I can't find the way to trigger the commands of virtualenvwrapper in shell. But this trick can help: assume your env. name is myenv, then put following lines at the beginning of scripts:
ENV=myenv
source $WORKON_HOME/$ENV/bin/activate
This is a super old thread and I had a similar issue. I started digging for a simpler solution out of curiousity.
gnome-terminal --working-directory='/home/exact/path/here' --tab --title="API" -- bash -ci "workon aaapi && python manage.py runserver 8001; exec bash;"
The --workingdirectory forces the tab to open there by default under the hood and the -ci forces it to work like an interactive interface, which gets around the issues with the venvwrapper not functioning as expected.
You can run as many of these in sequence. It will open tabs, give them an alias, and run the script you want.
Personally I dropped an alias into my bashrc to just do this when I type startdev in my terminal.
I like this because its easy, simple to replicate, flexible, and doesn't require any fiddling with variables and whatnot.
It's a known issue. As a workaround, you can make the content of the script a function and place it in either ~/.bashrc or ~/.profile
function run-app() {
workon "$(cat .venv)"
python main.py
}
If your Python script requires a particular virtualenv then put/install it in virtualenv's bin directory. If you need access to that script outside of the environment then you could make a symlink.
main.py from virtualenv's bin:
#!/path/to/virtualenv/bin/python
import yourmodule
if __name__=="__main__":
yourmodule.main()
Symlink in your PATH:
pymain -> /path/to/virtualenv/bin/main.py
In bin/run-app:
#!/bin/sh
# cd into the project directory
pymain arg1 arg2 ...
Apparently, I was doing this the wrong way. Instead of saving the virtualenv's name in the .venv file, I should be putting the virtualenv's directory path.
(cdvirtualenv && pwd) > .venv
and in the bin/run-app, I put
source "$(cat .venv)/bin/activate"
python main.py
And yay!
add these lines to your .bashrc or .bash_profile
export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
and reopen your terminal and try
You can also call the virtualenv's python executable directly. First find the path to the executable:
$ workon myenv
$ which python
/path/to/virtualenv/myenv/bin/python
Then call from your shell script:
#!/bin/bash
/path/to/virtualenv/myenv/bin/python myscript.py

Altering my python path: helloworld.py returns command not found—

Massive apologies for this embarrassing question—
I'm using my MacBook Pro, running snow leopard, and using Python 2.7.1. Trying to run my first script and all the first pages of all my tutorials are laughing at me:
Let me preface with:
$ whereis python
/usr/bin/python
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
(Is this my issue?)
I wrote helloworld.py to /users/charles in vim:
$ vim helloworld.py
#!/usr/bin/python
# Hello World Python Program
print "Hello World!";
When trying to run it from terminal:
$ helloworld.py
-bash: helloworld.py: command not found
When trying to run it from python:
$ python
>>> helloworld.py
Traceback (most recent call last):
File :<stdin>", line 1, in <module>
NameError: name 'helloworld' is not defined
From Dive Into Python (not sure if this is pertinent):
$ python
>>> import sys,os
>>> print 'sys.argv[0] =',sys.argv[0]
sys.argv[0]=
>>> pathname=os.path.dirname(sys.argv[0])
>>> print 'path=',pathname
path=
>>> print 'full path=',os.path.abspath(pathname)
full path= /Users/charles
I'm befuddled! Do I need to alter one of my paths so it finds my script?
I'm absolutely new to programming, I actually just found out that terminal was something you could use.
Thanks!
Let's start with the first error you received. Understanding error messages is important.
-bash: helloworld.py: command not found
This indicates that helloworld.py is not a command that can be executed. To run the file, you then have two options:
Run it using the python interpreter. python helloworld.py
Make the file executable and then run it directly. ./helloworld.py
To make files executable in a *nix environment, you have to change their mode to allow execution. In order to do this, you use the chmod command (man chmod for more info).
chmod +x helloworld.py
This assumes that you are in the directory containing the helloworld.py file. If not, cd there first or use the full path.
The ./ is necessary because it tells the shell to run the file located here, not by looking in $PATH. $PATH is a list of possible executable locations. When you try to run helloworld.py directly, the shell tries to look for it in $PATH. You want to run the local file, so you have to prefix it with ./, which means "from here".
As an aside, note the first line of your python script:
#!/usr/bin/python
This is called a shebang line and tells system to use the /usr/bin/python executable to load the file. Internally, that means that the program loader will be doing /user/bin/python helloworld.py.
Finally, when you called python with no arguments, you were dropped into an interactive Python interpreter session. >>> helloworld.py in this environment is not referencing the file of that name, it's just interpreted as python code. Invalid python code. This is why you get your second error, NameError: name 'helloworld' is not defined.
To turn a Python module or script into a standalone program on a UNIX system you have to do two things:
1.) Make sure you have the "shebang" in the top of your script:
#!/usr/bin/python
2.) Make sure the script file is executable. This is done using the chmod command:
chmod +x /path/to/helloworld.py
/path/to/ being the fully qualified file path to your script. If it's in the current directory, then you can omit the path.
% ls -l
total 0
drwxr-xr-x 2 jathan jathan 60 2011-04-13 15:28 ./
drwxrwxrwt 12 root root 6.5K 2011-04-13 15:28 ../
-rw-r--r-- 1 jathan jathan 0 2011-04-13 15:28 helloworld.py
It's in my current directory, so let's make it executable!
% chmod +x helloworld.py
% ls -l
drwxr-xr-x 2 jathan jathan 60 2011-04-13 15:28 ./
drwxrwxrwt 12 root root 6.5K 2011-04-13 15:28 ../
-rwxr-xr-x 1 jathan jathan 0 2011-04-13 15:28 helloworld.py*
See the "x"s in the permission bits on the left? You've done it! Now we can run it:
% ./helloworld.py
Hello World!
Lastly, never use semicolons as line-endings in Python. It's not required and it's ugly!
Wanted to add my 2 cents: Apart from permissions and path answers above, there is one more situation where you may still face the same error.
In-spite of correct permissions and the shebang header, you may still get the same "Command not found" error if you've originally written the file in Windows and copied it over to Linux. Due to differing line-ending characters, there will be extra '\r' characters on the lines.
This happens because there are non-printable characters in the file. Examing it by doing:
cat -v <filename>:
#!/usr/intel/bin/python^M
The extra "^M" is the problem. Use 'dos2unix' to convert the file and then it'll run fine.
as others said you should chmod +x your file to make it executable and if you don't want to put "./" in your coomand line you should add your current place as system path:
export PATH=$PATH:.
If you're already within python, the syntax to load your script is not helloworld.py :
import helloworld
or
from helloworld import *
you only use the extension .py when you're running python with a script as a command line argument.
No need to apologize, have to start somewhere, and the error messages can be cryptic when you're having basic syntax problems.
Make sure your terminal's current working directory is where your .py file is.
EDITED:
try doing /usr/bin/python helloworld.py on commmand line

Categories

Resources