【问题标题】:Print variable line by line with string in front Python 2.7用前面的字符串逐行打印变量 Python 2.7
【发布时间】:2017-03-19 00:34:12
【问题描述】:

我正在用 Python 编写一个侦察工具,但在尝试在多行变量前面打印一个字符串而不编辑字符串本身时遇到了一些问题

这是我的一小段代码:

# ...
query1 = commands.getoutput("ls -1 modules/recon | grep '.*\.py$' | grep -v '__init__.py'")
print("module/%s/%s" % (module_type, query1.strip(".py"))

我想添加“module/#module_type/#module_name”并且模块名称是唯一改变的东西。因此,使用 shodan 和 bing 模块(随机),输出将如下所示:

modules/recon/shodan
modules/recon/bing

但我得到了

modules/recon/bing.py
shodan

谢谢!

【问题讨论】:

    标签: python python-2.7 line-by-line


    【解决方案1】:

    你可以这样做:

    from os import path
    
    module_type = 'recon'
    q = 'shoban.py\nbing.py'  # insert the your shell invocation here
    modules = (path.splitext(m)[0] for m in q.split('\n'))
    formatted = ('modules/%s/%s' % (module_type, m) for m in modules)
    print('\n'.join(formatted))
    

    输出:

    modules/recon/shodan
    modules/recon/bing
    

    但是既然你已经从 python 调用了一个 unix shell,你还不如使用sed 来处理字符串:

    print(commands.getoutput("ls modules/recon/ | sed '/.py$/!d; /^__init__.py$/d; s/\.py$//; s/^/modules\/recon\//'"))
    

    如果您要查找模块的位置(例如模块/侦察)与您需要输出的前缀匹配,您还可以使用 shell 的“通配符”功能使命令更简单:

    print(commands.getoutput("ls modules/recon/*.py | sed 's/.py$//; /\/__init__$/d'"))
    

    另一种选择是只使用 python 的标准库:

    from os import path
    import glob
    
    module_type = 'recon'
    module_paths = glob.iglob('modules/recon/*.py')
    module_files = (m for m in map(path.basename, modules) if m != '__init___.py')
    modules = (path.splitext(m)[0] for m in module_files)
    formatted = ("modules/%s/%s" % (module_type, m) for m in modules)
    print('\n'.join(formatted))
    

    【讨论】:

    • 这是吹毛求疵,但您可以使用 os.path.splitext 来摆脱文件扩展名而不是文字 s[-3]
    • @АндрейБеньковский 看来我不小心不接受它。代码运行良好,我得到了它的工作。谢谢!
    猜你喜欢
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2012-12-12
    • 2019-10-17
    • 2015-12-30
    • 1970-01-01
    • 2018-05-09
    相关资源
    最近更新 更多