在Window仿Linux终端命令学习Python
- Echox 命令 -- 主要带颜色输出
- ls 命令
- findx 命令
- ~~待续~~
python3
Echox 命令 – 主要带颜色输出
查看 python输出颜色(终端控制台)
ls 命令
1、getopt
模块参数解析 : Python 命令行参数
2、os.getcwd()
获取当前目录
3、os.listdir(path)
返回path路径下文件列表。os.path.isfile、os.path.isdir
文件和目录判断
4、os.getenv
系统环境属性获取
5、colorama
库实现颜色输出:python输出颜色(终端控制台)
6、pyinstall
打包:Python程序打包为exe执行文件
7、win+R : sysdm.cpl
环境变量path中设置添加程序 ls.exe 路径
# ! /usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import os
import getopt
import cmdcolor
exts = os.getenv('PATHEXT').lower().split(';')
def isExt(filename):
if os.path.isfile(filename):
for ext in exts:
if filename.lower().rfind(ext) >= 0:
return True
return False
# ===========================================
def main(argv):
try:
opts, args = getopt.getopt(argv, "df")
except getopt.GetoptError:
print('getopt.GetoptError: ' + " ".join(str(n) for n in argv))
sys.exit(2)
for opt, arg in opts:
if opt in ['-d']:
for dirname in os.listdir(os.getcwd()):
if os.path.isdir(dirname):
print(cmdcolor.code_to_b256chars(2) + dirname + cmdcolor.RESET)
elif opt in ['-f']:
for dirname in os.listdir(os.getcwd()):
if os.path.isfile(dirname):
if isExt(dirname):
print(cmdcolor.code_to_f256chars(2) + dirname + cmdcolor.RESET)
else:
print(dirname)
if len(opts) == 0:
for dirname in os.listdir(os.getcwd()):
if isExt(dirname):
print(cmdcolor.code_to_f256chars(2) + dirname + cmdcolor.RESET)
elif os.path.isdir(dirname):
print(cmdcolor.code_to_b256chars(2) + dirname + cmdcolor.RESET)
else:
print(dirname)
if __name__ == '__main__':
main(sys.argv[1:])
findx 命令
1、getopt
模块参数解析 : Python 命令行参数
2、os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
目录和子目录下的文件
3、fnmatch.filter
支持正则表达式的匹配
4、os.getcwd()
获取当前目录
# ! /usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import os
import getopt
import fnmatch
def search_file(filename):
# print("xhbruce search_file: " + str(filename))
for root, dirs, files in os.walk(os.getcwd()):
for file in fnmatch.filter(files, filename):
print(os.path.join(root, file))
def search_file2(filename):
# print("xhbruce search_file2: " + str(filename))
for root, dirs, files in os.walk(os.getcwd()):
if root == os.getcwd():
for file in fnmatch.filter(files, filename):
print(os.path.join(root, file))
def main(argv):
try:
opts, args = getopt.getopt(argv, "s")
except getopt.GetoptError:
print("getopt.GetoptError: argv = " + str(argv))
sys.exit(2)
# print("xhbruce : " + str(opts) + str(args))
for opt, arg in opts:
if opt in ['-s']:
search_file(args[0])
if len(opts) <= 0:
if len(args) > 0:
search_file2(args[0])
if __name__ == '__main__':
main(sys.argv[1:])