python指令执行——exec
2019-03-19 本文已影响2人
MA木易YA
exec语句用来执行储存在字符串或文件中的Python语句。
exec("print('Hello World')")
运行结果:
Hello World
示例
这里我们用上一篇博客的内容来做这个示例,test.txt存储的是所有执行命令的字符串,我们读取到字符串后用exec执行
test.txt:
fake.city() # 城市名称
fake.street_name() # 街道名称
fake.country_code() # 国家编号
fake.longitude() # 经度
fake.address() # 地址
fake.latitude() # 纬度
fake.street_address() # 街道地址
fake.city_suffix() # 市
fake.postcode() # 邮政编码
fake.country() # 国家
fake.street_suffix() # 街道后缀
fake.building_number() # 建筑编号
fake.license_plate() # 车牌号
fake.rgb_css_color() #颜色RGB
fake.safe_color_name() # 颜色名称
fake.company() # 公司名
fake.credit_card_number(card_type=None) # 信用卡卡号
fake.date_time(tzinfo=None) # 随机日期时间
fake.file_extension(category=None) # 文件扩展信息
fake.ipv4(network=False) # ipv4地址
image.png
在主函数中我们直接读取字符串调用执行即可
from faker import Faker
if __name__ == '__main__':
fake = Faker()
datas = open('test.txt', encoding='utf-8').read().splitlines()
for data in datas:
print(data)
cmd = "print({})".format(data.split(' ')[0])
exec(cmd)
print("*****************************")
image.png