繁体   English   中英

执行.py文件,在for循环中调用python function

[英]execute .py file, call python function in for loop

我有一个 function 'plot_rdm',它创建一个 plot 并将其保存为 'rdm.png'。 我希望形成其中的几个图,每个图都使用不同的.json 文件 - 所以我将 function plot_rdm 保存在“plotrdm.py”中。

In the saverdm.py file - I defined the filepath of the.json file I want to create a plot from and then called the plot_rdm function, looping over all of the files I want to create a plot from:

#import libraries
import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import os
import json 

# define fpath 
#i.e. fpath[0] will be the first filepath... 

path = './RDM_researchproject' 
rootdir = path
filepath = []
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.startswith('Meadows'):
            count=0 # count default
            filepath.append(os.path.join(subdir, file))
            fpath = filepath[count]
            os.system("/home/taran/RDM_researchproject/AVIMA/plotrdm.py")
            count +=1      

带有 plot_rdm function 的 plotrdm.py 文件如下:

def plot_rdm(fpath):
    import numpy as np
    import matplotlib
    import matplotlib.pyplot
    import matplotlib.pyplot as plt
    import scipy
    import scipy.spatial
    import scipy.spatial.distance as sd
    from scipy.spatial.distance import squareform
    import json 
    
    with open(fpath) as fhandle:
        data = json.load(fhandle)
     #inspect rdm stimuli labels 
    stim = data['stimuli']

    #contain all labels for y axis and x axis seperately  
    y_names = []
    for i in stim:
        y_names.append(i['name'])

    x_names = []
    for i in stim:
        x_names.append(i['name'])

    #create rdm array and squareform 
    rdm_array = np.array(data['rdm'])
    srdm = squareform(rdm_array)

    #label x and y axis on rdm 
    fig, ax = plt.subplots()
    rdm = ax.imshow(srdm)

    ax.set_xticks(np.arange(len(x_names)))
    ax.set_yticks(np.arange(len(y_names)))

    ax.set_xticklabels(x_names)
    ax.set_yticklabels(y_names)
    plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
    plt.plot(srdm)
    plt.imshow(srdm)
    plt.colorbar(mappable = None, cax = None, ax = None)
    fig.subplots_adjust(bottom=0.23)
import matplotlib.pyplot as plt
plt.savefig('rdm.png')

我能够单独创建图(即,当我不调用 plot_rdm function 并遍历文件但我每次都指定文件路径时)。 但是当我使用下面的代码时,我在 AVIMA 文件夹中得到了一个空的 plot 。 我不确定导致这种情况发生的 saverdm 文件有什么问题?

https://github.com/Taranks7/RDM_researchproject如果我还没有解释清楚发生了什么,这就是我正在做的项目。

谢谢

当你想从另一个文件调用 python function 时,你不应该尝试通过调用 os.system 来运行另一个os.system进程。 只需导入 function: from plotrdm import plot_rdm

我们可以使用漂亮的 python 库glob来大量清理代码,而不是使用os.filewalkfile.startswith检查。 enumerate了一个很好的措施。

您的新rdmsave.py

import glob

from plotrdm import plot_rdm

basedir = "."

if __name__ == "__main__":
    count = 0
    for count, path in enumerate(sorted(glob.glob(f'{basedir}/**/Meadow*.json', recursive=True)), start=1):
        print(f"processing {path}")
        output_image = f'rdm_{count - 1:02}.png'
        print(f"output image will be {output_image}")
        plot_rdm(path, output_image)
    print(f"processed {count} files")

请注意,您可能需要将basedir更改回本地路径。

你的plotrdm.py变成:

import numpy as np
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
import scipy
import scipy.spatial
import scipy.spatial.distance as sd
from scipy.spatial.distance import squareform
import json
import matplotlib.pyplot as plt


def plot_rdm(fpath, output_filename):
    with open(fpath) as fhandle:
        data = json.load(fhandle)
        # inspect rdm stimuli labels

    stim = data['stimuli']

    # contain all labels for y axis and x axis seperately
    y_names = []
    for i in stim:
        y_names.append(i['name'])

    x_names = []
    for i in stim:
        x_names.append(i['name'])

    # create rdm array and squareform
    rdm_array = np.array(data['rdm'])
    srdm = squareform(rdm_array)

    # label x and y axis on rdm
    fig, ax = plt.subplots()
    rdm = ax.imshow(srdm)

    ax.set_xticks(np.arange(len(x_names)))
    ax.set_yticks(np.arange(len(y_names)))

    ax.set_xticklabels(x_names)
    ax.set_yticklabels(y_names)
    plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
    plt.plot(srdm)
    plt.imshow(srdm)
    plt.colorbar(mappable=None, cax=None, ax=None)
    fig.subplots_adjust(bottom=0.23)

    plt.savefig(output_filename)

我将第二个参数output_filename添加到plot_rdm function 以便可以将每个图像存储在一个新文件中。

我机器上的 output 读取

processing ./5/Meadows_avima-image-version1_v_v2_vital-macaw_2_tree.json
output image will be rdm_00.png
processing ./4/Meadows_avima-image-version1_v_v2_quick-louse_2_tree.json
output image will be rdm_01.png
processing ./1/Meadows_avima-image-version1_v_v2_better-hound_2_tree.json
output image will be rdm_02.png
processing ./3/Meadows_avima-image-version1_v_v2_huge-falcon_2_tree.json
output image will be rdm_03.png
processing ./2/Meadows_avima-image-version1_v_v2_guided-koi_2_tree.json
output image will be rdm_04.png
processed 4 files

并且在当前文件夹中创建了 4 个 png 文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM