使用特殊命令iceweasel(这是debian的firefox web浏览器)执行脚本

时间:2014-06-19 11:11:09

标签: python

我有一个问题,我想执行我的python脚本但是使用这样的特殊命令:

iceweasel 'info.py server.py path_install.py'

必须在客户端上键入此命令,我们打开包含信息的页面:

info.py (= os and ip of client)
server.py
path_install.py

但我真的不明白从哪里开始......

1 个答案:

答案 0 :(得分:1)

要求审核

看来,你想:

  • 从命令行调用程序
  • 传入任意数量的python文件名
  • 为每个python文件打印一些有关该文件的详细信息

概念

  • 使用docopt进行命令行参数解析(argparseplac,其他也是替代方案)
  • 打印一些有关该文件的信息(因为它不是很清楚,有关您要报告的Python文件的详细信息 - 根据需要进行修改)

iceweasel.py

"""
Usage:
    iceweasel.py <pythonfile>...
    iceweasel.py -h

Prints internal details for arbirtary set of <pythonfile> files.
"""
import os

def srcdetails(fname):
    with open(fname) as f:
        content = f.read()
    shortname = os.path.split(fname)[-1]
    size = len(content)
    words = len(content.split())
    templ = """
    ---- {fname} -----
    short name: {shortname}
    size: {size}
    words: {words}
    """
    print templ.format(**locals())

def main(pythonfiles):
    for fname in pythonfiles:
        srcdetails(fname)

if __name__ == "__main__":
    from docopt import docopt
    args = docopt(__doc__)
    pythonfiles = args["<pythonfile>"]
    main(pythonfiles)

使用

首先安装docopt

$ pip install docopt

不带参数调用命令:

$ python iceweasel.py
Usage:
    iceweasel.py <pythonfile>...
    iceweasel.py -h

尝试帮助

$ python iceweasel.py -h
Usage:
    iceweasel.py <pythonfile>...
    iceweasel.py -h

Prints internal details for arbirtary set of <pythonfile> files.

将它用于一个文件:

$ python iceweasel.py iceweasel.py 

    ---- iceweasel.py -----
    short name: iceweasel.py
    size: 692
    words: 74

使用通配符将其用于多个文件:

$ python iceweasel.py ../*.py

    ---- ../camera2xml.py -----
    short name: camera2xml.py
    size: 567
    words: 47


    ---- ../cgi.py -----
    short name: cgi.py
    size: 612
    words: 63


    ---- ../classs.py -----
    short name: classs.py
    size: 485
    words: 44

结论

  • 命令行解析在Python中很容易
    • argparse似乎是自2.7版本以来Python的标准部分。
    • argparse可以做很多事,但需要在很多行上进行相当复杂的调用
    • plac是不错的选择,在大多数情况下可以快速服务
    • docopt在我看来是最灵活的,同时也是所需代码行中最短的
  • 如果您不想在每次调用脚本时调用python,则可以选择其他方法
    • 使用shebang #!/usr/bin/env python作为脚本的第一行,将其设置为可执行文件,然后您甚至可以删除.py扩展名。仅适用于* nix,不适用于Windows
    • 编写您自己的setup.py并对其进行任务以安装脚本。无处不在,但需要更多编码。另一方面,如果您希望更多用户使用该脚本,它可以是非常有效的解决方案,因为它可以显着简化安装过程。