python 关于linux命令行

python 使用命令行

Use python to set env

读取环境变量

1
2
3
4
5
6
7
8
9
10
# Import os module  
import os

# Iterate loop to read and print all environment variables
print("The keys and values of all environment variables:")
for key in os.environ:
print(key, '=>', os.environ[key])

# Print the value of the particular environment variable
print("The value of HOME is: ", os.environ['HOME'])

查看环境变量是否设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Import os module  
import os
# Import sys module
import sys

while True:
# Take the name of the environment variable
key_value = input("Enter the key of the environment variable:")

# Check the taken variable is set or not
try:
if os.environ[key_value]:
print("The value of", key_value, " is ", os.environ[key_value])
# Raise error if the variable is not set
except KeyError:
print(key_value, 'environment variable is not set.')
# Terminate from the script
sys.exit(1)

设置环境变量

1
2
3
4
5
6
7
8
9
10
11
# Import os module  
import os

# Set the value DEBUG variable
os.environ.setdefault('DEBUG', 'True')

# Checking the value of the environment variable
if os.environ.get('DEBUG') == 'True':
print('Debug mode is on')
else:
print('Debug mode is off')

设置命令行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import subprocess
import os
def command(command_line):
process = subprocess.Popen(command_line,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stderr = stderr.decode('utf-8')
stdout = stdout.decode('utf-8')
print("stdout ",stdout,";stderr ",stderr)

command(['command','arg','aeg'])

def split_str_by_blank(str_com,split_char = ""):

# str 是字符串,默认用空格分割

# para

# @str_com -> string 待分割的字符串

# @split_char -> string 分割标志

# @return -> list 分割输出

if not split_char:

str_list = str_com.split()

else:

str_list = str_com.split(split_char)

return str_list


def command_print_out_err(str_com):

# 用来执行命令,并且根据是否报错输出err 或者 out

# para

# @str_com -> string 输入命令

# @print 输出 err 或者 out

str_list = split_str_by_blank(str_com)

err , out = commandline(str_list)

if err :

print("ERROR ! : \n",err)

elif out :

print("OUTPUT : \n",out)

踩坑

  • 不要使用 str , command 之类的关键字作为函数/函数名,都可能会报 str object is not callable

python 关于linux命令行
http://home.ustc.edu.cn/~ustcxwy0271/2022/03/31/python-develop-1/
作者
Xu Weiye
发布于
2022年3月31日
许可协议