通过python面向对象编程运行图形

2024-10-03 21:27:59 发布

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

我的问题是关于用python输入对象的

我试图创建一个对象,打开这个python文件,它要求我输入一个数据文件的路径,我输入路径,它会为我打印一个数据图

到目前为止,我有:

def graph_openprices():
while True:
    try:
        from matplotlib import pyplot as plt
        from matplotlib import style
        import numpy as np
        path_openprices = input("Input file path_g: ")

        style.use('ggplot')

        x,y = np.loadtxt(path_openprices, unpack = True, delimiter= ',')
        plt.plot(x,y)

        plt.title('My chart')
        plt.ylabel('Y axis')
        plt.xlabel('X axis')

        plt.show()

        anykey = input("Input anything to return to the main menu ")
        exit

    except OSError:
        print("Directory incorrect, please input a valid directory")
        graph_openprices()

graph_openprices()

我正在运行这个代码,但是,每次它要求我输入我的代码,我输入它

D:\Mycode\exampleFile.txt

什么都没有发生,什么都没有出现,这只是空间。但是,当我通过在前面放置一个#来停用path_openprices行,并在x,y变量中键入path_openprices所在的路径时,它就起作用了

有人知道我做错了什么,以及我如何使输入部分工作吗


Tags: path对象fromimport路径trueinputmatplotlib
2条回答

while True循环中,只使用try和特定的匹配异常,因此如果发生其他错误,将不会告诉您它是什么

使用print语句查看代码在似乎什么都没做的情况下正在做什么

您正在使用input,它试图以Python代码的形式对给定的输入求值。请参阅documentation,它告诉您它相当于运行eval(raw_input(...))

$ echo 'D:\MyCode\lol.txt' | python -c 'input()'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1
    D:\MyCode\lol.txt
     ^
SyntaxError: invalid syntax

您通常不希望计算用户给定的任意字符串,因此请改用^{}

相关问题 更多 >