1

I have been trying to print several equations I have using numpy and matplotlib.

The functions are stored on a text file, one equation per line. These equations look like this: np.exp(6.6506+(-171.637)/(x*32))

My idea was to iterate to each line, generate the plot and save it somewhere. My code:

import numpy as np
import matplotlib.pyplot as plt

source = "path/to/list.txt"

with open(source) as f:
    for line in f.readlines():
        x = np.linspace(0,200)
        y = line
        plt.plot(x,y)
        plt.savefig(str( line + ".png"))
        plt.close()

I get the results I want by removing the loops part and replacing y = line by y = np.exp(6.6506+(-171.637)/(x*32))

How can I plot all equations in my txt file? Plots are very simple and 2D.

1 Answer 1

2

Use eval, with the usual reservations regarding security:

y = eval(line)

you may have to remove the new line \n from the lines you read from file with line.strip('\n')



drawing attention to eval security risks:

eval parses a string (any string given to it) and attempts to execute it... This is why it is generally considered a security risk and must only be used when it is certain that no malicious or harmful instructions will ever be passed to it. The risks involved are not trivial and the consequences potentially disastrous.

more about the dangers of eval - suggested by @Brenogil

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! What does eval() do in this case?
eval parses a string (any string given to it) and attempts to execute it... This is why it is generally considered a security risk and must only be used when it is certain that no malicious or harmful instructions will ever be passed to it. The risks involved are not trivial and the consequences potentially disastrous.
Thanks! This solved it. Your clarifications were quite nice. I also checked this post: eval really is dangerous

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.