在shell中使用date命令 注意代码中的括号是全角,运行前要改成半角,否则出错。
$((运算内容))
可用于执行整数运算,比如$((5*3))
用于执行乘法,{firstnu}*${secnu}))执行两个变量相乘。
bash xx.sh
与source xx.sh
区别在于变量是否在父进程生效。
test
加参数,可用于判断文件的存在,权限,字符串,文件新旧等。
if else
if condition
then commands
elif condition
then commands
else
commands
fi
function
python调用shell
How to Execute Shell Commands with Python写得好
Python subprocess.Popen 实时输出 stdout
中文输出/usr目录
list_files = subprocess.Popen(["ls", "-l", "/usr"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line_bytes in list_files.stdout.readlines():
print(line_bytes.decode('utf-8'), end='')
输出
/usr/bin/python3.6 /home/rasak/PycharmProjects/demo/shell.py
总用量 96
drwxr-xr-x 2 root root 49152 4月 15 00:36 bin
drwxr-xr-x 2 root root 4096 2月 4 02:25 games
drwxr-xr-x 35 root root 4096 4月 14 04:51 include
drwxr-xr-x 128 root root 4096 4月 14 04:44 lib
drwxr-xr-x 3 root root 4096 4月 14 01:23 libexec
drwxr-xr-x 11 root root 4096 4月 15 00:10 local
drwxr-xr-x 2 root root 12288 4月 13 18:15 sbin
drwxr-xr-x 263 root root 12288 4月 14 04:51 share
drwxr-xr-x 6 root root 4096 4月 13 18:15 src
Process finished with exit code 0
systemctl
.service文件用于定义服务,一般放置于/lib/systemd/system
,其内容一般如下格式:
[Unit]
Description=Echo hello world
[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/bin/echo-service.py
其中ExecStart
对应systemctl start xx
启动时的指令。
通过自定义.service文件,我们可以创建自己的服务
自定义python服务实践
创建python脚本
rasak@rasak-lee:/lib/systemd/system$ sudo nano /usr/bin/echo-service.py
import os
file_dir = os.path.join("/home/rasak", "文档")
file_name = "hello-world.txt"
file_path = os.path.join(file_dir, file_name)
if os.path.exists(file_dir):
with open(file_path, "w") as f:
f.write("hello world!")
else:
print("路径不存在")
创建service
rasak@rasak-lee:/lib/systemd/system$ sudo nano /lib/systemd/system/hello-world.service
[Unit]
Description=Echo hello world
[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/bin/echo-service.py
启动服务
rasak@rasak-lee:/lib/systemd/system$ systemctl start hello-world
之后在/home/rasak/文档下可看到文件hello-world.txt
网友评论