首页 / PYTHON / Core Python | 1 - Python: The Big Picture | 1.3 - When and Where Is Python Being Used | 1.3.2 - Linux Scripting and Administration
Core Python | 1 - Python: The Big Picture | 1.3 - When and Where Is Python Being Used | 1.3.2 - Linux Scripting and Administration
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Core Python | 1 - Python: The Big Picture | 1.3 - When and Where Is Python Being Used | 1.3.2 - Linux Scripting and Administration,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含7567字,纯文字阅读大概需要11分钟。
内容图文
![Core Python | 1 - Python: The Big Picture | 1.3 - When and Where Is Python Being Used | 1.3.2 - Linux Scripting and Administration](/upload/InfoBanner/zyjiaocheng/1181/63f60a0bd0d442aa9e067be72e267c7d.jpg)
One of the first areas we‘ll discuss where Python is being used is in the world of Linux scripting and administration. When we are scripting to administer a machine, we obviously have a machine that lies at the heart of it. There are lots of things we may want to interact with and do with that machine as well. We routinely work with folders and files on the machine. We might be managing a series of log files or simply examining and monitoring the file system. Of course, one common reason to interact with the file system is when dealing with the configuration of apps and services. We may want to monitor the processes running on a system, keeping an eye on any potential runaway processes that need to be kept in check. Or, we may want to launch new processes as part of our scripting process. We might want to deploy a new application or deploy a version of an existing app onto that machine. We may even want to remove older applications that are no longer needed. Finally, we could even be running scripts to execute various test suites. These could be used to make sure the machine itself is healthy to validate existing apps and services on the machine, or we might be intentionally breaking apps and services to test how resilient our various systems are in the presence of failures. There are many different things you may want to use scripting for, and with Python as a vehicle, the main limit is our imagination. We have full access to the wide variety of Python libraries that are already out there or that we can create from scratch.
So let‘s dive in and take a quick look at two simple scenarios you may encounter in this area, working with files and working with processes.
Let‘s start by working with files. We have a JSON file that contains some data. Let‘s take a look. As you can see, it‘s a JSON object that contains a name and a list of hobbies. We‘ll start by creating a new Python file called input.py. The first thing we do is to import the JSON module, as this will allow us to easily work with the JSON data we‘re going to suck in from the input JSON file. To get the data, we use the open function and give it the name of our file and specify we‘re opening it up in read?only mode. By using the with statement, the file handle will automatically be closed when the code block exits. Once we have the file open, all we need to do is use json.load to load the data from our input file into a Python object we can work with. For now, we‘ll just use the name from the object to say hello to. We save the file and change back to our terminal. We execute the file using Python 3, and we can see our message printed to the command line like we expect.
[root@izbp1eednvvtf33syjd02az system]# pwd /root/Source/personal/pluralsight/python/system [root@izbp1eednvvtf33syjd02az system]# lsinput.json input.py [root@izbp1eednvvtf33syjd02az system]# cat input.json{ "name": "Jason", "hobbies": ["music", "programming", "games"], "job": "Software Developer" } [root@izbp1eednvvtf33syjd02az system]# cat input.pyimport json with open(‘input.json‘, ‘r‘) as input: obj = json.load(input) print(‘Hello, ‘ + obj[‘name‘]) [root@izbp1eednvvtf33syjd02az system]# python input.pyHello, Jason [root@izbp1eednvvtf33syjd02az system]#
- input.json文件包含了字典和列表结构,但是它是一个字符串
- 使用open方法打开input.json,参数r表示read-only,文件的内容赋给变量input。open的时候使用with语句,代码执行完毕,文件会自动被关闭
- 使用json模块将字典和列表结构load出来,赋给变量obj
- print一句话,‘Hello, Jason’,其中Jason是通过obj[‘name‘]查询字典而来
So let‘s change our code to also write to a file to see the other side of the equation. Similar to reading a file, we just use the open function to open a file to write to. This time we use w, for write mode, and use the with statement again to automatically close the file handle when we‘re done with it. We start by writing out the name and prepare to print out the name of the hobbies listed in the JSON object. To iterate over the hobbies, we‘ll just use a for statement over the array in our JSON object. For each hobby, we simply call the write method on our file object to write a string to the file. A quick save of the file, and then we can execute it again using Python 3. It runs successfully with no errors. To see the output, let‘s print the contents of our output.txt file to the screen. We can see the format we expected printed out. As we saw, working with files is very straightforward and simple.
[root@izbp1eednvvtf33syjd02az system]# ls input.json input.py [root@izbp1eednvvtf33syjd02az system]# cat input.json { "name": "Jason", "hobbies": ["music", "programming", "games"], "job": "Software Developer" } [root@izbp1eednvvtf33syjd02az system]# cat input.py import json with open(‘input.json‘, ‘r‘) as input: obj = json.load(input) with open(‘output.txt‘, ‘w‘) as output: output.write(obj[‘name‘] + "‘s Hobbies:\n") for hobby in obj[‘hobbies‘]: output.write(hobby + "\n") [root@izbp1eednvvtf33syjd02az system]# python input.py [root@izbp1eednvvtf33syjd02az system]# ls input.json input.py output.txt [root@izbp1eednvvtf33syjd02az system]# cat output.txt Jason‘s Hobbies:music programming games [root@izbp1eednvvtf33syjd02az system]#
- 打开input.json文件(r只读模式),使用json模块将字典和列表结构load出来
- 打开output.txt文件(w可写模式,末尾追加)
- 写入1行‘Jason‘s Hobbies:’,回车
- 遍历hobbies列表,写入3行,每行1个hobby
For the last part of the demo, let‘s switch over and take a brief look at one way we can work with processes.
First, we‘ll create a new file called process.py. In this file, we‘re going to list all the running processes on the system as a child process to our running code, and then we‘ll use a pipe to communicate with that child process so we can retrieve the output of the process we executed. The first thing we need to do is import the subprocess module that enables us to easily work with child processes in Python. All we‘re going to do is use the Popen function, for process open, in the subprocess module to execute our ps command as a child process. We specify that standard out of our child process is a pipe that we can then communicate directly with. After the subprocess is executed, its results can be found in the variable pl. The variable pl, in this case, will be a byte array containing the output of the command we executed. So we will decode the output as a Unicode string and just print it to the console. After we save the file and switch back to the terminal, we can execute it using Python 3. As we can see, it lists out all the running processes in the system as a child process and printed its contents out to the console, just like we expected.
[root@izbp1eednvvtf33syjd02az system]# ls input.json input.py output.txt process.py [root@izbp1eednvvtf33syjd02az system]# cat process.py import subprocess pl = subprocess.Popen([‘ps‘, ‘-U‘, ‘0‘], stdout=subprocess.PIPE).communicate()[0] print(pl.decode(‘utf-8‘)) [root@izbp1eednvvtf33syjd02az system]# python process.py PID TTY TIME CMD 1 ? 00:00:16 systemd 2 ? 00:00:00 kthreadd ……
…… 31546 pts/100:00:00 python 31547 pts/100:00:00ps [root@izbp1eednvvtf33syjd02az system]#
- 使用subprocess创建子进程
- 在子进程中使用Popen()方法执行Linux系统命令‘ps -U 0’,命令执行结果输出给PIPE
- 使用communicate()方法,去PIPE中获取信息
scripting to administer | 写脚本来管理... |
interact | 互动 |
routinely | 日常地,例行地 |
examining and monitoring the file system | 检查和监控文件系统 |
runaway processes | 失控的进程 |
suite | 套件 |
execute various test suites | 执行各种测试套件 |
validate | 证实,验证有效 |
intentionally | 故意地 |
resilient | 有弹性的 |
in the presence of failures | 面对失败 |
with Python as a vehicle | 用Python作为载体 |
from scratch | 从头开始,白手起家 |
原文:https://www.cnblogs.com/hmlhml/p/14265293.html
内容总结
以上是互联网集市为您收集整理的Core Python | 1 - Python: The Big Picture | 1.3 - When and Where Is Python Being Used | 1.3.2 - Linux Scripting and Administration全部内容,希望文章能够帮你解决Core Python | 1 - Python: The Big Picture | 1.3 - When and Where Is Python Being Used | 1.3.2 - Linux Scripting and Administration所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。