Create your own Linux commands in Python

About this article

Python is used for various purposes these days, but it is also useful when you want to automate small tasks such as file operations!

[Let Python do the boring things](https://www.amazon.co.jp/%E9%80%80%E5%B1%88%E3%81%AA%E3%81%93%E3% 81% A8% E3% 81% AFPython% E3% 81% AB% E3% 82% 84% E3% 82% 89% E3% 81% 9B% E3% 82% 88% E3% 81% 86-% E2% 80 % 95% E3% 83% 8E% E3% 83% B3% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9E% E3% 83% BC % E3% 81% AB% E3% 82% 82% E3% 81% A7% E3% 81% 8D% E3% 82% 8B% E8% 87% AA% E5% 8B% 95% E5% 8C% 96% E5 % 87% A6% E7% 90% 86% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82 There is even a book called% B0-Al-Sweigart / dp / 487311778X). ↑ I'm not an affiliate (just in case)

In this article, I'll show you how to execute such Python code as if it were a command!

procedure

This time, we will follow the steps while creating a command to display the file list, `filelist```. (Something like ls``)

If you want to introduce the procedure in one word ** Give execute permission to the file "filelist" that specifies the python interpreter (`#! / usr / bin / env python```) in Shebang, and put the file in the saved directory in the PATH. Can be executed with filelist ``. ** ** It's like that.

The implementation flow is shown below.

0. Premise

It is assumed that Python is already installed and can be executed with the `` `python``` command. If you search for "python installation linux" etc., various methods will appear, so please refer to it.

1. Script creation

First, create a script to execute. Create an appropriate folder and save it in it.

  1. Create a "pycommands" directory in your home directory
mkdir ~/pycommands
  1. Move to the "pycommands" directory
cd ~/pycommands
  1. Create a file "filelist" and go to the edit screen
vi filelist
  1. Edit the file "filelist"
#!/usr/bin/env python

import os
from pathlib import PATH

#The directory where the user is currently (os.getcwd()) Get information
current_dir = PATH(os.getcwd())

# glob("*")Get a list of files in the directory where the user is currently
for file in current_dir.glob("*"):
    print(file)

The important thing here is the `#! / Usr / bin / env python``` on the first line. This is called ** Shebang ** and specifies what to use to interpret the contents of the file. Since Python is specified here, Python code is executed even if it is not written as `.py```. (If you specify Ruby etc. in this part, you can also execute Ruby code.)

2. Grant execution authority

The file "filelist" you just created is not a file that can be executed yet. To do this, you need to give the file ** execute permissions **.

To give execute permission to a file

chmod u+x ~/pycommands/filelist

To execute. (It is assumed that "filelist" is created under `~ / pycommands /`. If you create it in a different location, change the command accordingly.)

//qiita.com/shisama/items/5f4c4fa768642aad9e06)



 In this state, the execution itself can already be performed.
 At any place

```shell
~/pycommands/filelist

When you enter the command, a list of files should be output.

The next step will allow you to do this by simply typing filelist.

3. Pass through PATH

Then make it possible to run this command from anywhere.

In order to be able to execute a command located in a certain place from anywhere, it is necessary to set the PATH environment variable.

Roughly speaking, PATH is "a list of places to go to find an executable file with that name when you enter a ** command (likely thing) **".

lsWhen I enter the command, it goes looking for an executable file named "ls" in the path and runs the file I find. (Searching while accessing the location list defined in PATH one by one from the front.)

For the time being, to execute only this time

export PATH='$PATH:$HOME/pycommands/'

It is OK if you execute.

To be able to use it all the time

echo export PATH='$PATH:$HOME/pycommands/' >> ~/.bashrc
source ~/.bashrc

Is OK.

4. Run!

Wherever you are

filelist

If you execute, a list of files will be displayed.

If not executed

There is already a command with the same name

If a command with the same name already exists, the command with the same name as the command created in this flow already exists, so it will be searched for first in the PATH and the created command will not be executed. (Because I added a directory at the end of PATH)

Change the name or change the order of the PATH so that it will be executed first. (Not recommended)

Summary

Let's make a command to make the work convenient ^ ^

Recommended Posts

Create your own Linux commands in Python
[LLDB] Create your own command in Python
Create your own Big Data in Python for validation
Create your own Random Dot Stereogram (RDS) in Python.
[Python] logging in your own module
Easily use your own functions in Python
Get your own IP address in Python
Create your own graph structure class and its drawing in python
Create your own exception
Create SpatiaLite in Python
Import your own modules in Grasshopper's Python development
Create a package containing global commands in Python
Memo to create your own Box with Pepper's Python
Create a function in Python
Create a dictionary in Python
Take your own peak memory usage on Linux & Python
Try to improve your own intro quiz in Python
Run shell commands in python
Create gif video in Python
[Blender × Python] Create your own function & summary so far
Use the CASA Toolkit in your own Python environment
Create your first GDSII file in Python using gdspy
Create your own Django middleware
[Road to intermediate Python] Define in in your own class
Try sorting your own objects with priority queue in Python
[Python] Make your own LINE bot
Check for external commands in python
Make your own manual. [Linux] [man]
8 Frequently Used Commands in Python Django
Create a DI Container in Python
Handle dates in Linux bash commands
How to create your own Transform
Create a binary file in Python
Create Gmail in Python without API
[Linux] [kernel module] Create kthread in kernel module
Create your own name resolution service
[Django] Create your own 403, 404, 500 error pages
Create Python project documentation in Sphinx
Create a Kubernetes Operator in Python
Create a random string in Python
Create and read messagepacks in Python
Linux commands
Linux commands
linux commands
Try docker: Create your own container image for your Python web app
Linux commands
Linux commands
Specify your own class in class argument and return type annotation in Python
Create wordcloud from your tweet with python3
Create ScriptableObject in Python when building ADX2
Find files like find on linux in Python
[Linux] List of Linux commands used in practice
Create your own DNS server with Twisted
Create a python environment on your Mac
[Python] Package and distribute your own modules
Create a simple GUI app in Python
Create your own Composite Value with SQLAlchemy
Create a JSON object mapper in Python
Create Qt designer parts in Python (PyQt)
[Python] Register your own library on PyPI
Until you install your own Python library