在python中从非.py文件执行代码 [英] Execute code from non .py file in python

查看:56
本文介绍了在python中从非.py文件执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让 python 执行给定文件中的随机代码行.假设我有一个名为code_lines"的文件.该文件包含随机的 Python 代码片段,例如

I am trying to make python execute a random line of code from a given file. Let's say I have a file called "code_lines". This file contains random pieces of python code, ex.

print("This is a random message")
print("This is another message")
print("This is getting boring")

python 是否可以从该文件中随机选择一行并将其作为代码运行?

Is it possible for python to select a random line from that file and run it as code?

推荐答案

尝试使用 exec 语句.当然,这在实际情况下可能会导致几个问题,因为您试图从文件中执行随机行,但它适用于简单的代码行(例如您在示例 code_lines.py<中提供的代码行)/代码>).

Try making use of exec statement. Of course, this can cause several problems in a real case scenario, since you are trying to execute random lines off a file, but it works for simple lines of code (like the ones you supplied in your example code_lines.py).

from random import randint

with open('code_lines.py') as file:
    line = file.readline()
    count = 0
    code =[]
    while line:
        code += [line]
        line = file.readline()
        count += 1
    exec(code[randint(0,count-1)])

这篇关于在python中从非.py文件执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆