在Python2.7前面用字符串逐行打印变量

2024-05-20 16:06:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面是我的代码:

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

我想添加“module/#module#u type/#module#u name”,并且module name是唯一改变的东西。因此,使用shodan和bing模块(随机)输出如下:

modules/recon/shodan
modules/recon/bing

但是我得到了

modules/recon/bing.py
shodan

谢谢!你知道吗


Tags: 工具字符串代码namepymodules编辑type
1条回答
网友
1楼 · 发布于 2024-05-20 16:06:25

你可以这样做:

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\//'"))

如果要查找模块(例如modules/recon)的位置与需要输出的前缀匹配,您还可以使用shell的“globbing”功能简化命令:

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))

相关问题 更多 >