Почему я получаю сообщение «[Win error 2] Система не может найти указанный файл» при использовании ani.save для python 3.7.6? - PullRequest
0 голосов
/ 10 апреля 2020

Я получаю сообщение об ошибке «не могу найти файл» при попытке сохранить анимированные сюжеты как * .mp4, используя ani.save в моем коде. Я использую Spyder вер. 4.0.1 для IDE и python ver 3.7.6. Я установил ffmpeg с помощью pip install, но все еще сталкиваюсь с той же проблемой.

Это код, который был разработан на предыдущем компьютере, отличном от моего. В настоящее время я использую Windows 10 64-битный ноутбук. Я вырезал большую часть кода, поскольку он очень длинный, чтобы показать часть анимации, с которой у меня возникают проблемы.

Кто-нибудь сможет узнать причину, по которой я сталкиваюсь с блокпостом с python анимация?

Спасибо!

Код

import csv
import numpy as np
import scipy
from scipy import pi
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import matplotlib.animation as animation
from matplotlib import rcParams
import time
from pstats import Stats

'...Some file reading and calculation code which is ommited...'

 # Pressure and Temp Movie

    R2 = np.flipud(R)              # reversed order of R for plotting versus depth into sphere

    # Set up formatting for the movie files
    writer = animation.FFMpegFileWriter(fps=20,bitrate=1800)

    # Pressure Animation
    fig = plt.figure(10,figsize=(9.75,5.625))
    plt.title("Shell Temperature and Pressure v Shell Depth: \n" + str(Ns) +" shells " + '{:,}'.format(Nt)+" timesteps"+"\n")
    plt.xlabel("Depth (m)")
    plt.ylabel("Temperature (K)")
    ax = plt.gca()                      # Labeling the axis variable of the plot for formatting
    ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
    ax.yaxis.set_major_formatter(mtick.FuncFormatter(lambda x, p: format(int(x), ',')))
    line1, = plt.plot(R2,T[0],'r-',label="Temperature")
    ax2 = plt.twinx()
    ax2.yaxis.set_major_formatter(mtick.FuncFormatter(lambda x, p: format(int(x), ',')))
    ax2.set_ylabel("Pressure (Pa)")
    line2, = plt.plot(R2,P[0],'k-',label="Total Pressure")
    volLines=[]
    for p in range(Uv):
        if uniqueVol[p] == 'H2O':
            volLines.append(ax2.plot(R2,unique_PP[p,0],'b-'))
        else:
            volLines.append(ax2.plot(R2,unique_PP[p,0]))

    time_text = ax.text(np.amax(R2)*0.5,np.amax(T)*0.9,'',horizontalalignment='center',verticalalignment='top',fontsize=15)
    time_text.set_text("0 hr")
    h1, l1 = ax.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()


    for spine in ['left','right','top','bottom']:
        ax2.spines[spine].set_color('k')

    def animate(i):
        t = (Time[StepPerFrame*i]//1)
        time_text.set_text("%.f hours" % t)
        line1.set_ydata(T[StepPerFrame*i])
        line2.set_ydata(P[StepPerFrame*i])
        for p in range(Uv):
            volLines[p][0].set_ydata(unique_PP[p,StepPerFrame*i])
        return volLines, line1, line2, time_text
    plt.xlim([np.amin(R2),np.amax(R2)])
    ax.set_ylim([0,((Thot+100)//100)*100])
    ax2.set_ylim([np.amin(P),((np.amax(P)+1000)//1000)*1000])
    ax.set_yticks(np.linspace(ax.get_ybound()[0], ax.get_ybound()[1], 5))
    ax2.set_yticks(np.linspace(ax2.get_ybound()[0], ax2.get_ybound()[1], 5))
    ax.set_autoscale_on(False)
    leg1 = ax.legend(l1, loc="upper right")
    leg1.get_frame().set_edgecolor('k')
    leg1.get_frame().set_facecolor('w')
    leg2 = ax2.legend(l2+list(uniqueVol), loc="center right", title="Gas Partial Pressures")
    leg2.get_frame().set_edgecolor('k')
    leg2.get_frame().set_facecolor('w')
    ani = animation.FuncAnimation(fig,animate,frames=(len(Time)//StepPerFrame),interval=50)
    print("Plots Done")
    print("Saving Pressure Animation...")
    start = time.time()
    ani.save('TempPressMovie.mp4',writer=writer)
    end  = time.time()
    print("Pressure Movie Done")
    print(end - start)
    plt.clf()

Ошибка


  File "C:\Research\Thermal Mining Model\MineSimVer36hr offset.py", line 1735, in <module>
    MineSim("MineSim Input9 JBWm 50.txt")

  File "C:\Research\Thermal Mining Model\MineSimVer36hr offset.py", line 1599, in MineSim
    ani.save('TempPressMovie.mp4',writer=writer)

  File "C:\Users\PC\anaconda3\lib\site-packages\matplotlib\animation.py", line 1156, in save
    writer.grab_frame(**savefig_kwargs)

  File "C:\Users\PC\anaconda3\lib\contextlib.py", line 119, in __exit__
    next(self.gen)

  File "C:\Users\PC\anaconda3\lib\site-packages\matplotlib\animation.py", line 232, in saving
    self.finish()

  File "C:\Users\PC\anaconda3\lib\site-packages\matplotlib\animation.py", line 527, in finish
    self._run()

  File "C:\Users\PC\anaconda3\lib\site-packages\matplotlib\animation.py", line 363, in _run
    creationflags=subprocess_creation_flags)

  File "C:\Users\PC\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\PC\anaconda3\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\PC\anaconda3\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...