0

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

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

  • You can run `python your_file.whatever`, and it'll try to execute the file as Python code, but it won't be able to execute 'random lines'. It would try to treat the data in this file as ordinary Python code, though. – ForceBru Apr 21 '18 at 19:09
  • This question has already been asked. Please see: https://stackoverflow.com/questions/31704916/python-how-to-execute-code-from-a-txt-file – Anish Shanbhag Apr 21 '18 at 19:09
  • You can use `exec`. Unfortunately I can no longer place an answer. – CristiFati Apr 21 '18 at 19:22

2 Answers2

1

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)])
officialaimm
  • 378
  • 4
  • 16
0

Use the random module to choose randomly, and exec to execute arbitrary Python code.

import random

with open('code_lines') as f:
    exec(random.choice(f.readlines()))

Warnings: exec and eval are super dangerous. If someone else could write code to code_lines they can do pretty much whatever they want to your computer. Also, if the line of code you select is dependent on other lines, it could potentially fail.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96