Python脚本必须运行两次才能执行

时间:2017-01-09 18:45:32

标签: python matplotlib

我编写了一个python脚本来收集和分析.csv文件中的数据,然后使用matplotlib.pyplot模块绘制它。我正在使用numpy.genfromtext()来收集数据。

我第一次运行该文件时,没有任何反应。我收到控制台消息:

>>> runfile('C:/my_filepath/thing.py')

仅此而已。如果我再次运行该文件,然后执行,打印出来的东西,情节出现等等:

runfile('C:/my_filepath/thing.py')
~the stuff it's supposed to print~

更多信息:这个问题只发生在我的笔记本电脑上,这让我觉得它与我的matplotlib安装有关(对我来说很神秘,因为我在桌面上安装了一个相同的Anaconda软件包,没有问题)。在笔记本电脑上,绘图窗口是独立的,在桌面上,绘图显示在控制台中。也许那是相关的。

有人有这个问题吗?

edit2:只有当我尝试在同一个控制台中多次运行程序时才会发生这种情况。如果我在一个新的控制台中运行脚本它工作正常,那么你必须为每次执行运行它两次。如果我关闭matplotlib窗口,杀死控制台,并打开一个新的,我每次都可以执行它。

编辑:这是一个展示奇怪行为的工作示例。不要取笑我的代码 - 我在周末学习了python

import re
import numpy as np
from numpy import genfromtxt as gft
import matplotlib.pyplot as plt

def getnames(Pattern):
    #construct the list of files in the directory
    CSVList = []
    for FileName in os.listdir():
        if re.compile(Pattern).search(FileName):
            CSVList.append(FileName)

    print(len(CSVList), 'files found.')


    #sort the list by the integer values of the last 4 digits of the    filename
    CSVList.sort(key=lambda x: int(x.rsplit('.')[0][-4:]))


    return CSVList

def xy_extract(Data):
    x = np.array([row[0] for row in Data])
    y = np.array([row[1] for row in Data])

    return x, y

CSVList = getnames('(?i)\.csv$')
print(CSVList)

#plt.figure(figsize=(10,5))
plt.xlim(799,3999)

for Filename in CSVList:
    Data = gft(Filename, delimiter=',',skip_header=2)
    x, y = xy_extract(Data)

    plt.plot(x, y,label=Filename)

plt.show()

0 个答案:

没有答案