用python编写bash_如何用Python作为您的命令行语言替换Bash

用python编写bash

I have a bit of a love and hate relationship with bash. I spend a lot of time in the terminal, and bash is my default "programming language". Sometimes I tell people that find, grep and xargs run their infrastructure, and they laugh and laugh until they realize I'm serious.

我对bash有点爱与恨。 我在终端上花了很多时间,而bash是我的默认“编程语言”。 有时我告诉人们find,grep和xargs运行着他们的基础架构,他们笑着笑直到意识到我是认真的。

Picking up some Python is a perfect choice for system administrators. It's also great for anyone who has to deal with anything in a terminal but doesn't want to use bash, or has needs that are too complex for bash. Once a task goes beyond

挑选一些Python是系统管理员的理想选择。 对于必须在终端中处理任何事情但又不想使用bash或对bash过于复杂的需求的人来说,这也很棒。 一旦任务超越

find $(pwd) -name "*.txt" | xargs -I {} echo "do stuff with {}"

it's time to break out the Python!

现在是时候发布Python了!

There are a lot of benefits to using Python as your go to command line language.

将Python用作命令行语言有很多好处。

  • Python has lots of nice libraries to help out with pretty much anything. That includes dealing with system operations, reading files, listing directories, writing for loops, checking for exit codes, and so on.

    Python有很多不错的库,可以帮助您解决几乎所有问题。 这包括处理系统操作,读取文件,列出目录,编写循环,检查退出代码等。
  • Autocomplete with IDEs. Seriously. Who wants to have to memorize anything?

    使用IDE自动完成。 说真的 谁想记住任何东西?
  • Robust testing suite if that's your thing (and if it's not, you should consider making it your thing).

    健壮的测试套件是否适合您(如果不是,则应考虑将其用作您的东西)。
  • The iPython console. It's wonderful. It's amazing. I LOVE IT.

    iPython控制台。 太好了 太奇妙了。 我喜欢它。

  • Python is available on most systems, and if it's not you can get it with Miniconda.

    Python在大多数系统上都可用,如果没有,则可以通过Miniconda获得。

  • Robust error checking with try and catch blocks.

    使用try和catch块进行健壮的错误检查。
  • If you work on different operating systems you can use Python libraries that will deal with all that under the hood.

    如果您在不同的操作系统上工作,则可以使用Python库来处理所有这些问题。
  • Even if you have no programming ability Python is an easy language to get started with.

    即使您没有编程能力,Python还是很容易上手的语言。

让我们开始吧 (Let's get Started)

To get started, first off you'll need to either have Python installed or install it with Miniconda.

首先,您首先需要安装Python或使用Miniconda进行安装。

检查是否已安装iPython (Check if you have iPython installed)

which python
which ipython

If both of these are successful, you're in business! If you have Python, but not iPython, you will have to install it. You could install it as a system package, but I really recommend that you just install it with Miniconda.

如果这两项都成功,那么您就是在做生意! 如果您拥有Python,但没有iPython,则必须安装它。 您可以将其安装为系统软件包,但我确实建议您仅使用Miniconda进行安装。

安装Miniconda (Install Miniconda)

Grab the installer for your OS here. I suggest getting the Python3 installation.

此处获取适用于您的OS的安装程序。 我建议安装Python3。

Then it's just a simple installation.

然后,这只是一个简单的安装。

bash Miniconda3-latest-Linux-x86_64.sh

Follow the prompts and you'll have Miniconda3 installed. Once you have it installed you'll want to run an update, because this is tech and of course you want to run an update. ;-)

按照提示进行操作,您将安装Miniconda3。 安装完成后,您将要运行更新,因为这是技术性的,当然您要运行更新。 ;-)

conda update conda
conda config --add channels conda-forge
conda update -y --all
conda install -y ipython

故障排除 (Troubleshooting)

If you have trouble installing any packages here are some tips.

如果您在安装任何软件包时遇到问题,请参考以下提示。

  • Run conda clean --all and try again.

    运行conda clean --all然后重试。

  • Make sure you're using the correct channel.

    确保您使用的频道正确。
  • Run conda update -y --all

    运行conda update -y --all

  • Try to install as little as possible to your global conda space. Instead create environments for different tasks and projects, which we will get into next.

    尝试尽可能少地安装到全局conda空间。 而是为不同的任务和项目创建环境,我们接下来将介绍它们。

使用Conda创建环境 (Create Environments with Conda)

If you've ever used virtualenv, pipenv (is that a thing?), Rbenv, plenv, anyenv or any of the other various envs that have popped up over the years, this will sound very familiar to you. The idea is that different projects should have their own isolated software environments.

如果您曾经使用过virtualenv,pipenv(是这样吗?),Rbenv,plenv,anyenv或这些年来涌现的其他各种环境中的任何一种,那对您来说听起来很熟悉。 想法是,不同的项目应具有自己的隔离软件环境。

conda create -n my-project ipython package1 package2 package2

If you're like me and like to have iPython readily availabe make sure you install it to any new environments!

如果您像我一样,并且喜欢随时使用iPython,请确保将其安装到任何新环境中!

用于系统管理的Python库 (Python Libraries for System Administration)

Before we get into the examples let's just list some handy packages along with their docs.

在进入示例之前,我们只列出一些方便的软件包及其文档。

My go to package is the os package. You can use it to list directories, check if files exist, check if symlinks exist, make directories, run system commands, get and set environmental variables, and more. It's great!

我的软件包是os软件包。 您可以使用它来列出目录,检查文件是否存在,检查符号链接是否存在,创建目录,运行系统命令,获取和设置环境变量等等。 这很棒!

My second package for running system commands that don't exist as handy python libraries is the subprocess module.

我的第二个用于运行不作为方便的python库存在的系统命令的程序包是subprocess模块。

The shutil has file operations that aren't in the os library.

shutil的文件操作不在os库中。

The pprint library prints out complex data structures with nice indentation.

pprint库以精巧的缩进打印出复杂的数据结构。

The pytest library let's you test your Python code, because let's face it, nothing ever works correctly the first (few) times.

pytest库让您测试您的Python代码,因为面对它,第一次(很少)都无法正常工作。

如何执行我的代码? (How Do I Execute my Code?)

Finally! Code!

最后! 码!

Screenshot-2019-12-13-10.33.52

When you're using Python for system administration you can dive straight into the iPython console, or write scripts and then execute them with python name-of-script.py.

使用Python进行系统管理时,您可以直接进入iPython控制台,或者编写脚本,然后使用python name-of-script.py执行它们。

If you prefer to write your scripts you have so many choices, and it's truly a matter of personal preference. I use PyCharm, which is paid, but Visual Studio Code and Atom are equally excellent free choices.

如果您喜欢编写脚本,那么可以有很多选择,这实际上是个人喜好问题。 我使用PyCharm ,它是付费的,但是Visual Studio CodeAtom都是同样出色的免费选择。

I find that it depends on what I'm working on. Sometimes I just open up the iPython console and start typing, and other times I need something more robust with tests and whatnot.

我发现这取决于我的工作。 有时,我只是打开iPython控制台并开始输入内容,而其他时候,我需要更强大的测试和其他功能。

If you're using either the iPython console or any of the editors I listed above, you will have autocomplete. Autocomplete is awesome! With iPython simply start typing your function and press tab to get a list of potential functions you may want.

如果您使用的是iPython控制台或上面列出的任何编辑器,则将具有自动完成功能。 自动完成功能很棒! 使用iPython,只需开始键入您的函数,然后按Tab键即可获取可能需要的潜在函数列表。

Screenshot-2019-12-13-10.49.07

I cannot express how much I love autocomplete. ;-)

我无法表达我有多喜欢自动完成功能。 ;-)

得到帮助 (Get Help)

You can go to any of the doc pages for any library, but if you know the name of either the library or the function you can bring it up in iPython.

您可以转到任何库的任何文档页面,但是如果您知道该库或函数的名称,则可以在iPython中启动它。

Screenshot-2019-12-13-10.55.14

Screenshot-2019-12-13-10.55.55

You can bring up the help menu in most IDEs and text editors too, but that will be specific to your editor.

您也可以在大多数IDE和文本编辑器中调出帮助菜单,但这将特定于您的编辑器。

例子 (Examples)

First you will need to import your packages

首先,您需要导入软件包

import os
import subprocess
import shutil
from pprint import pprint

Here are some examples of common file and directory operations.

以下是一些常见文件和目录操作的示例。

# Get your current working directly
# This returns a string
my_cwd = os.getcwd()
print(my_cwd)
# List the contents of a directory
# This returns a list
dir_list = os.listdir()
for item in dir_list:
    print(item)
# Get the Absolute Path name of a file (file + current working dir)
os.path.abspath('some-file')
#Get the basename - returns file
os.path.basename('/path/to/file')
# Split a directory path - platform independent
os.path.split(os.getcwd())
# Out[17]: ('/Users', 'jillian')
# Check if a path exists
os.path.exists('/path/on/filesystem')
# Check if a path is a symlink
os.path.islink()

Move files and directories around

移动文件和目录

# Copy a directory
# cp -rf
shutil.copytree('src', 'dest')
# Copy a file
# cp -rf
shutil.copyfile('file1', 'file2')
# Move a directory
# mv
shutil.move('src', 'dest')

Not everything is going to be available through python libraries, such as installing system libraries, so run a few system commands!

并非所有内容都可以通过python库获得,例如安装系统库,因此请运行一些系统命令!

# Run an arbitrary system command
command = "echo 'hello'"
result = subprocess.run(command.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#Print the stdout and stderr
print(result.stdout)
print(result.stderr)

Write to files!

写文件!

# Write to a file (and create it if it doesn't exist)
# echo "hello" > hello.txt
f= open("hello.txt","w+")
f.write("hello!")
f.close()
# Append to a file
# echo "hello" >> hello.txt
f = open("hello.txt", "a+")
f.write("hello again!")
f.close()

写一些测试! (Write some tests!)

Tests mostly work by using a function called assert, which is essentially saying make sure this is true and if not die loudly.

测试通常通过使用一个称为assert的函数来工作,该函数实质上是在确保这是正确的,如果不是很大的话就会死掉。

def test_system_command():
    """Test the exit code of a system command"""
    command = "echo 'hello'"
    result = subprocess.run(command.split(' '), stdout=subprocess.PIPE)
    assert result.returncode == 0

Put this function in a file called test_my_code.py and run as pytest test_my_code.py.

将此函数放在一个名为test_my_code.py的文件中,并作为pytest test_my_code.py运行。

结语 (Wrap Up)

That's it for my main tips and tricks for using Python as your go-to bash replacement. The next time you need to write a loop in bash, consider breaking out the iPython console and seeing what you can come up with instead!

这就是我使用Python替代bash的主要技巧和窍门。 下次您需要在bash中编写循环时,请考虑突破iPython控制台,然后看看您能想到什么!

翻译自: https://www.freecodecamp.org/news/python-for-system-administration-tutorial/

用python编写bash

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值