Python 练习

2018-05-01  本文已影响0人  AIfred

命令行执行的相关库

os.system

该命令可以在终端中直接输出执行的结果,但是无法output存为一个变量,来使用。但是如果在写脚本的时候直接使用该命令可以让用户很直观地看到输出的内容

import os
#Use os.system to install openpyxl module
os.system("pip install openpyxl")
#输出结果
Requirement already satisfied: openpyxl in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages
Requirement already satisfied: jdcal in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages (from openpyxl)
Requirement already satisfied: et_xmlfile in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages (from openpyxl)

os.popen

print("####some lines")
print("####some lines")
print("####some lines")
#Use os.popen to install openpyxl module
output = os.popen("pip install openpyxl").read()
print(output)

print("####################")
output = output.split('\n')
for o in output:
    print(o)
####some lines                                                                                                                                                              
####some lines                                                                                                                                                              
####some lines
Requirement already satisfied: openpyxl in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages
Requirement already satisfied: jdcal in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages (from openpyxl)
Requirement already satisfied: et_xmlfile in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages (from openpyxl)
####################
Requirement already satisfied: openpyxl in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages
Requirement already satisfied: jdcal in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages (from openpyxl)
Requirement already satisfied: et_xmlfile in /home/alfredubuntu/anaconda3/lib/python3.6/site-packages (from openpyxl)

commands

可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位
已经在python3.x移除

subprocess

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.system
os.spawn*

Information about how the subprocess module can be used to replace these modules and functions can be found in the following sections.
See also
PEP 324 – PEP proposing the subprocess module

参考

参考1

上一篇下一篇

猜你喜欢

热点阅读