How do I alias a command line command? (Mac) - python

I'm on a mac, and I write quite a bit of python scripts.
Every time I need to run them, I have to type 'python script_name.py'. Is there I way to make it so I only have to type like 'p script_name.py'? It would save some time :D

I am assuming you are running your script from the command line right? If so, add the following line as the first line in your script:
#!/usr/bin/python
or alternatively
#!/usr/bin/env python
in case the python command is not located in /usr/bin, and then issue the following command once at the Unix/terminal prompt (it makes your script "executable"):
chmod +x script_name.py
from then on you only need to type the name of the script at the command prompt to run it. No python part of the command needed. I.e., simply
./script_name.py
will run the script.
You can also of course go with the alias, but the above is a cleaner solution in my opinion.
For the alias
alias p="python"
should go into your ~/.bashrc file

Use the alias command:
alias p="python"
You'll probably want to add this to your ~/.bashrc.

You can add an alias to your ~/.profile file:
alias p="python"
Note that you can also make a Python script executable with chmod +x script.py. You can then execute it using:
./script.py
You will need to add the following line to the top of your Python code for this to work:
#!/usr/bin/env python
This is called shebang.

You can add aliases in the ~/.zshrc file:
alias gs="git status"
alias gc="git commit -m"
alias ga="git add"
alias p="python"
Then close and reopen the terminal to apply the changes.

Related

Adding command-line in cmd

Is there any way to create a command on Command Prompt like I want to create a command named createdirectory(I know there is an existing command for that but take this as an example) . when i execute the command "createdirectory" it will run a python file. I want it in such a way that i can run this command from anywhere any disk volume or any folder.
If you know anything then please post your answer.
Thanks!
Shell commands are basically either aliases or programs stored on disk. You can write your programs put them in some directory and add that directory path to the shell's PATH variable.
Let's say you have a program called create.py which creates the directories. You can follow these two ways to make them available as command on a shell
Assume create.py is present in /home/bob/scripts directory
Create a wrapper script
Create a file called createDirectory with below content in /home/bob/scripts
python /home/bob/scripts/create.py $*
Add /home/bob/scripts to the PATH
export PATH="$PATH:/home/bob/scripts"
Using aliases
Run the alias command
alias createDirectory="python /home/bob/scripts/create.py"
Usage
createDirectory <whatever> <arguments> <your> <program> <expects>
NOTE: You can add this alias command and export command to ~/.bashrc file so that it is run when you start a shell

Create terminal name for execute python script in Ubuntu

I have a python file in: '/home/username/scripts/pyscript' and I want set a word for execute directly this script.
I want do this "python3 /home/username/scripts/pyscript/main.py arg1 arg2" but looks like
this "myscript arg1 arg2"
Is this posible?
Thank you anyway.
It is possibile in a number of ways. Links are for Bash, supposedly your shell but the ideas always apply.
First option: make a shell alias
alias myscript='python3 /home/username/scripts/pyscript/main.py'
Be sure to add the alias to your .profile to make it survive logout.
Second option: define a wrapper script. Create a file with the following content, named after your desired command (e.g. myscript):
#!/bin/bash
python3 /home/username/scripts/pyscript/main.py "$#"
save it and make it executable, then call it :
chmod +x myscript
./myscript arg1 arg2
Be sure to copy the script in a folder in your PATH (check where with echo $PATH) to be able to call it from any folder.
You can also use pyinstaller to create a single file executable:
Step 1: Install pyinstaller
[Note: best practice is to do this in a virutalenv]
$ pip install pyinstaller
Step 2: Run pyinstaller against your script
$ pyinstaller --console --onefile /home/username/scripts/pyscript
$ pyinstaller pyscript.spec # use this after the first run
Step 3: Test the generated executable
$ cd /home/username/scripts/dist # generated by pyinstaller
$ pyscript arg1 arg2
Step 4: Leverage the $PATH variable
$ cp /home/username/scripts/dist/pyscript /usr/bin
You should now be able to run the executable from anywhere.
It should be noted that the executable that is generated is OS specific. For example, if you generate it on an Ubuntu machine, it will only run on Ubuntu (Debian based). The same holds true for Windows and other Linux distros.
Finally I solver with the help of #pierpaciugo
I add a alias at the end of the .bashrc for make it persistent:
alias create='bash /home/username/Programming/Python/GithubAPI/script.sh'
I couldn't use only alias because I have my python dependencies on a virtual environment so if I try this i could not add params to my python script.
For that I create this bash script:
#!/bin/bash
source /home/username/Programming/Python/GithubAPI/venv/bin/activate && python3 /home/username/Programming/Python/GithubAPI/main.py $# && deactivate
Now I can write "create param1 param2" and it works.
I am using all global paths but could be a good idea add the script in a folder in my PATH.

How to keep a changed python working directory [duplicate]

I'm trying to write a small script to change the current directory to my project directory:
#!/bin/bash
cd /home/tree/projects/java
I saved this file as proj, added execute permission with chmod, and copied it to /usr/bin. When I call it by:
proj, it does nothing. What am I doing wrong?
Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The cd succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.
One way to get around this is to use an alias instead:
alias proj="cd /home/tree/projects/java"
You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.
You can run the script in your current process with the "dot" command:
. proj
But I'd prefer Greg's suggestion to use an alias in this simple case.
The cd in your script technically worked as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.
A Posix-compatible way to solve this problem is to define a shell procedure rather than a shell-invoked command script.
jhome () {
cd /home/tree/projects/java
}
You can just type this in or put it in one of the various shell startup files.
The cd is done within the script's shell. When the script ends, that shell exits, and then you are left in the directory you were. "Source" the script, don't run it. Instead of:
./myscript.sh
do
. ./myscript.sh
(Notice the dot and space before the script name.)
To make a bash script that will cd to a select directory :
Create the script file
#!/bin/sh
# file : /scripts/cdjava
#
cd /home/askgelal/projects/java
Then create an alias in your startup file.
#!/bin/sh
# file /scripts/mastercode.sh
#
alias cdjava='. /scripts/cdjava'
I created a startup file where I dump all my aliases and custom functions.
Then I source this file into my .bashrc to have it set on each boot.
For example, create a master aliases/functions file: /scripts/mastercode.sh
(Put the alias in this file.)
Then at the end of your .bashrc file:
source /scripts/mastercode.sh
Now its easy to cd to your java directory, just type cdjava and you are there.
You can use . to execute a script in the current shell environment:
. script_name
or alternatively, its more readable but shell specific alias source:
source script_name
This avoids the subshell, and allows any variables or builtins (including cd) to affect the current shell instead.
Jeremy Ruten's idea of using a symlink triggered a thought that hasn't crossed any other answer. Use:
CDPATH=:$HOME/projects
The leading colon is important; it means that if there is a directory 'dir' in the current directory, then 'cd dir' will change to that, rather than hopping off somewhere else. With the value set as shown, you can do:
cd java
and, if there is no sub-directory called java in the current directory, then it will take you directly to $HOME/projects/java - no aliases, no scripts, no dubious execs or dot commands.
My $HOME is /Users/jleffler; my $CDPATH is:
:/Users/jleffler:/Users/jleffler/mail:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work
Use exec bash at the end
A bash script operates on its current environment or on that of its
children, but never on its parent environment.
However, this question often gets asked because one wants to be left at a (new) bash prompt in a certain directory after execution of a bash script from within another directory.
If this is the case, simply execute a child bash instance at the end of the script:
#!/usr/bin/env bash
cd /home/tree/projects/java
echo -e '\nHit [Ctrl]+[D] to exit this child shell.'
exec bash
To return to the previous, parental bash instance, use Ctrl+D.
Update
At least with newer versions of bash, the exec on the last line is no longer required. Furthermore, the script could be made to work with whatever preferred shell by using the $SHELL environment variable. This then gives:
#!/usr/bin/env bash
cd desired/directory
echo -e '\nHit [Ctrl]+[D] to exit this child shell.'
$SHELL
I got my code to work by using. <your file name>
./<your file name> dose not work because it doesn't change your directory in the terminal it just changes the directory specific to that script.
Here is my program
#!/bin/bash
echo "Taking you to eclipse's workspace."
cd /Developer/Java/workspace
Here is my terminal
nova:~ Kael$
nova:~ Kael$ . workspace.sh
Taking you to eclipe's workspace.
nova:workspace Kael$
simply run:
cd /home/xxx/yyy && command_you_want
When you fire a shell script, it runs a new instance of that shell (/bin/bash). Thus, your script just fires up a shell, changes the directory and exits. Put another way, cd (and other such commands) within a shell script do not affect nor have access to the shell from which they were launched.
You can do following:
#!/bin/bash
cd /your/project/directory
# start another shell and replacing the current
exec /bin/bash
EDIT: This could be 'dotted' as well, to prevent creation of subsequent shells.
Example:
. ./previous_script (with or without the first line)
On my particular case i needed too many times to change for the same directory.
So on my .bashrc (I use ubuntu) i've added the
1 -
$ nano ~./bashrc
function switchp
{
cd /home/tree/projects/$1
}
2-
$ source ~/.bashrc
3 -
$ switchp java
Directly it will do: cd /home/tree/projects/java
Hope that helps!
It only changes the directory for the script itself, while your current directory stays the same.
You might want to use a symbolic link instead. It allows you to make a "shortcut" to a file or directory, so you'd only have to type something like cd my-project.
You can combine Adam & Greg's alias and dot approaches to make something that can be more dynamic—
alias project=". project"
Now running the project alias will execute the project script in the current shell as opposed to the subshell.
You can combine an alias and a script,
alias proj="cd \`/usr/bin/proj !*\`"
provided that the script echos the destination path. Note that those are backticks surrounding the script name.
For example, your script could be
#!/bin/bash
echo /home/askgelal/projects/java/$1
The advantage with this technique is that the script could take any number of command line parameters and emit different destinations calculated by possibly complex logic.
to navigate directories quicky, there's $CDPATH, cdargs, and ways to generate aliases automatically
http://jackndempsey.blogspot.com/2008/07/cdargs.html
http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5827311.html
In your ~/.bash_profile file. add the next function
move_me() {
cd ~/path/to/dest
}
Restart terminal and you can type
move_me
and you will be moved to the destination folder.
You can use the operator && :
cd myDirectory && ls
While sourcing the script you want to run is one solution, you should be aware that this script then can directly modify the environment of your current shell. Also it is not possible to pass arguments anymore.
Another way to do, is to implement your script as a function in bash.
function cdbm() {
cd whereever_you_want_to_go
echo "Arguments to the functions were $1, $2, ..."
}
This technique is used by autojump: http://github.com/joelthelion/autojump/wiki to provide you with learning shell directory bookmarks.
You can create a function like below in your .bash_profile and it will work smoothly.
The following function takes an optional parameter which is a project.
For example, you can just run
cdproj
or
cdproj project_name
Here is the function definition.
cdproj(){
dir=/Users/yourname/projects
if [ "$1" ]; then
cd "${dir}/${1}"
else
cd "${dir}"
fi
}
Dont forget to source your .bash_profile
This should do what you want. Change to the directory of interest (from within the script), and then spawn a new bash shell.
#!/bin/bash
# saved as mov_dir.sh
cd ~/mt/v3/rt_linux-rt-tools/
bash
If you run this, it will take you to the directory of interest and when you exit it it will bring you back to the original place.
root#intel-corei7-64:~# ./mov_dir.sh
root#intel-corei7-64:~/mt/v3/rt_linux-rt-tools# exit
root#intel-corei7-64:~#
This will even take you to back to your original directory when you exit (CTRL+d)
I did the following:
create a file called case
paste the following in the file:
#!/bin/sh
cd /home/"$1"
save it and then:
chmod +x case
I also created an alias in my .bashrc:
alias disk='cd /home/; . case'
now when I type:
case 12345
essentially I am typing:
cd /home/12345
You can type any folder after 'case':
case 12
case 15
case 17
which is like typing:
cd /home/12
cd /home/15
cd /home/17
respectively
In my case the path is much longer - these guys summed it up with the ~ info earlier.
As explained on the other answers, you have changed the directory, but only within the sub-shell that runs the script. this does not impact the parent shell.
One solution is to use bash functions instead of a bash script (sh); by placing your bash script code into a function. That makes the function available as a command and then, this will be executed without a child process and thus any cd command will impact the caller shell.
Bash functions :
One feature of the bash profile is to store custom functions that can be run in the terminal or in bash scripts the same way you run application/commands this also could be used as a shortcut for long commands.
To make your function efficient system widely you will need to copy your function at the end of several files
/home/user/.bashrc
/home/user/.bash_profile
/root/.bashrc
/root/.bash_profile
You can sudo kwrite /home/user/.bashrc /home/user/.bash_profile /root/.bashrc /root/.bash_profile to edit/create those files quickly
Howto :
Copy your bash script code inside a new function at the end of your bash's profile file and restart your terminal, you can then run cdd or whatever the function you wrote.
Script Example
Making shortcut to cd .. with cdd
cdd() {
cd ..
}
ls shortcut
ll() {
ls -l -h
}
ls shortcut
lll() {
ls -l -h -a
}
If you are using fish as your shell, the best solution is to create a function. As an example, given the original question, you could copy the 4 lines below and paste them into your fish command line:
function proj
cd /home/tree/projects/java
end
funcsave proj
This will create the function and save it for use later. If your project changes, just repeat the process using the new path.
If you prefer, you can manually add the function file by doing the following:
nano ~/.config/fish/functions/proj.fish
and enter the text:
function proj
cd /home/tree/projects/java
end
and finally press ctrl+x to exit and y followed by return to save your changes.
(NOTE: the first method of using funcsave creates the proj.fish file for you).
You need no script, only set the correct option and create an environment variable.
shopt -s cdable_vars
in your ~/.bashrc allows to cd to the content of environment variables.
Create such an environment variable:
export myjava="/home/tree/projects/java"
and you can use:
cd myjava
Other alternatives.
Note the discussion How do I set the working directory of the parent process?
It contains some hackish answers, e.g.
https://stackoverflow.com/a/2375174/755804 (changing the parent process directory via gdb, don't do this) and https://stackoverflow.com/a/51985735/755804 (the command tailcd that injects cd dirname to the input stream of the parent process; well, ideally it should be a part of bash rather than a hack)
It is an old question, but I am really surprised I don't see this trick here
Instead of using cd you can use
export PWD=the/path/you/want
No need to create subshells or use aliases.
Note that it is your responsibility to make sure the/path/you/want exists.
I have to work in tcsh, and I know this is not an elegant solution, but for example, if I had to change folders to a path where one word is different, the whole thing can be done in the alias
a alias_name 'set a = `pwd`; set b = `echo $a | replace "Trees" "Tests"` ; cd $b'
If the path is always fixed, the just
a alias_name2 'cd path/you/always/need'
should work
In the line above, the new folder path is set
This combines the answer by Serge with an unrelated answer by David. It changes the directory, and then instead of forcing a bash shell, it launches the user's default shell. It however requires both getent and /etc/passwd to detect the default shell.
#!/usr/bin/env bash
cd desired/directory
USER_SHELL=$(getent passwd <USER> | cut -d : -f 7)
$USER_SHELL
Of course this still has the same deficiency of creating a nested shell.

turn all files in a folder into function aliases with bash

I have a folder of python files. I want to turn them into functions I can call in bash. This following one-liner is in my profile text file loading at bash login, but it doesn't work. How can I fix it?
for i in `ls ~/Dropbox/Documents/tools/python`; do
fullfilename=$(basename "$i");
filename="${fullfilename%.*}";
$("alias $filename='/usr/local/bin/python3.3 ~/Dropbox/Documents/tools/python/$fullfilename '");
done
EDIT:
per Liviu Chircu's recommendation, I removed the " before and after the alias command. Following is now the new code:
for i in `ls ~/Dropbox/Documents/tools/python`; do
fullfilename=$(basename "$i");
filename="${fullfilename%.*}";
$(alias $filename='/usr/local/bin/python3.3 ~/Dropbox/Documents/tools/python/$fullfilename ');
done
Now I get this error:
$ findfactors 40
-bash: findfactors: command not found
Three steps to make the Python scripts executable from bash.
First, at the top of every file in that directory, add the following line to tell bash which interpreter to use.
#!/usr/local/bin/python3.3
Second, set all those files to executable.
chmod u+x ~/Dropbox/Documents/tools/python/*
Third, add that directory to your PATH. This one goes in ~/.bashrc, while the other two are one-time things.
export PATH=$PATH:$HOME/Dropbox/Documents/tools/python
Looks like you need to remove " from your alias command.
Try
$(alias $filename='/usr/local/bin/python3.3 ~/Dropbox/Documents/tools/python/$fullfilename ');
Instead of
$("alias $filename='/usr/local/bin/python3.3 ~/Dropbox/Documents/tools/python/$fullfilename '");
You mean something like
for i in "$HOME"/Dropbox/Documents/tools/python/*; do
fullfilename="$(basename "$i")"
filename="${fullfilename%.*}"
alias "$filename"="/usr/local/bin/python3.3 ~/Dropbox/Documents/tools/python/$fullfilename"
done

run a python script in terminal without the python command

I have a python script let's name it script1.py. I can run it in the terminal this way:
python /path/script1.py
...
but I want to run like a command-line program:
arbitraryname
...
how can i do it ?
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
There are three parts:
Add a 'shebang' at the top of your script which tells how to execute your script
Give the script 'run' permissions.
Make the script in your PATH so you can run it from anywhere.
Adding a shebang
You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:
#!path/to/interpretter
To find the path to your python interpretter on your machine you can run the command:
which python
This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:
#!/usr/bin/python
Run Permissions
You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:
chmod +x myscript.py
Add the script to your path
The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:
echo $PATH
This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:
which <commandname>
Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:
export PATH=/my/directory/with/pythonscript:$PATH
Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile
Add the following line to the beginning script1.py
#!/usr/bin/env python
and then make the script executable:
$ chmod +x script1.py
If the script resides in a directory that appears in your PATH variable, you can simply type
$ script1.py
Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH.
$ ./script1.py
You need to use a hashbang. Add it to the first line of your python script.
#! <full path of python interpreter>
Then change the file permissions, and add the executing permission.
chmod +x <filename>
And finally execute it using
./<filename>
If its in the current directory,

Categories