如何用Python写Linux命令
发布时间:2017-04-01 04:31
相关话题
在Linux中, 一切都是命令. 把多个单个的命令组合在一起, 可以创造出惊人的功能. Linux命令大多由c语言编写, 但是c语言开发太过繁琐, 如何能用Python编写Linux命令呢?下面就让小编给大家说说如何用Python写Linux命令吧。
用Python写Linux命令的方法
首先, 创建一个文件, 并给这个文件起一个名字, 该名字就是最后的命令, 例如add. 注意, 这个文件名字不必以py结尾. 然后给这个文件运行权限, 如下:

然后, 打开刚刚创建的文件, 将下面的代码写入头两行. 其中第一行说明这个文件由python解释器来运行, 第二行指定文件的编码.

之后, 导入标准模块argparse.

导入模块之后, 你可以写任何你想要做的功能, 不过要将功能封装成模块, 而不是直接运行, 这是出于良好的编程实践. 举个例子:

在文件的最下面, 解析命令行参数, 并调用上面写好的功能模块

最后, 保存退出. 在命令行里面运行这个文件,如下

如何用P
如何用Python写Linux命令的评论条评论