You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python subprocess.run()调用Normal.py返回code1问题求助

Python subprocess调用脚本返回returncode=1排查

我尝试使用Python的subprocess.run()方法运行Normal.py脚本,但执行完成后返回return code 1。以下是调用代码、Normal.py完整代码及错误信息,请求协助排查问题。

调用代码

import subprocess

print(subprocess.run(['python',rf'C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept15_2022\Test2\1\Normal.py']))

Normal.py完整代码

import os

Runs=2

def function(run):
    from scipy.stats import truncnorm
    import numpy as np
    import csv 
    # Create the folder with the number of the run as name
    # Add 1 to run so the first run is 1 and not 0
    parent_folder = str(run + 1)
    os.mkdir(parent_folder)

    a, b = 47.0,53.0
    Nodes=220  #reshape into
    r = (1e-6)*np.linspace(truncnorm.ppf(0.001, a, b),truncnorm.ppf(1.0, a, b), Nodes)
    print("r =",[r])

    sort_r = np.sort(r); 
    r1=sort_r[::-1]
    print("r1 =",[r1])
    #print("r =",[r])

    r1=r1.reshape(1,Nodes)
    print("r1 shape =",[r1])

    r2 = r.copy()

    # r2.ravel() returns a view of the original array
    # so we can shuffle only the items starting from 1
    np.random.shuffle(r2.ravel()[1:])
    print("r2 =",[r2])    

    r2=r2.reshape(1,Nodes)
    print("r2 =",[r2])                          #actual radius values in mu(m)

    maximum = r2.max()
    indice1 = np.where(r2 == maximum)
    # minimmum = r2.min()
    # indice2 = np.where(r2 == minimum)
    r2[indice1] = r2[0][0]
    r2[0][0] = maximum
    #print(r2)
    r2[0][Nodes-1] = maximum  #+0.01*maximum
    #print(r2)
    print("r2 with max at (0,0)=",[r2])

    ######################################

    # make a copy and shuffle the copy
    # r2 = r.copy()
    # np.random.shuffle(r2.ravel())

    # # get the index of the max
    # idx = np.unravel_index(r2.argmax(), r2.shape)

    # # swap first and max
    # r2[idx], r2[(0, 0)] = r2[(0, 0)], r2[idx]

    # print(r2)


    ######################################

    with open(os.path.join(parent_folder, 'Inv_Radius_220_47_53ND.csv'), 'w+') as f: 
        inv_r=1/r2
        print("inv_r =",[inv_r])
        writer = csv.writer(f)
        writer.writerows(inv_r)
     

    mean=np.mean(r)
    print("Mean =",mean)
    var=np.var(r)
    print("var =",var)
    std=np.std(r)
    print("std =",std)

    with open(os.path.join(parent_folder,'Radius info _220_47_53ND.txt'), 'w+') as f: 
        
            f.write(f"mean = {str(mean)}\n")
            f.write(f"var = {str(var)}\n")
            f.write(f"std = {str(std)}\n")


for x in range(Runs):
    function(x)

错误信息

CompletedProcess(args=['python', 'C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept15_2022\\Test2\\1\\Normal.py'], returncode=1)

排查与修复步骤

1. 先捕获脚本的真实错误输出

当前调用代码没有捕获Normal.py的标准输出和错误信息,无法知道具体报错原因。修改调用代码如下,直接查看脚本运行时的错误详情:

import subprocess

result = subprocess.run(
    ['python', rf'C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept15_2022\Test2\1\Normal.py'],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    encoding='utf-8'
)
print("返回码:", result.returncode)
print("脚本输出:", result.stdout)
print("错误详情:", result.stderr)

2. 针对代码预判的常见错误修复

  • 文件夹已存在报错:脚本中os.mkdir(parent_folder)若遇到已存在的1或2文件夹会直接崩溃。替换为os.makedirs(parent_folder, exist_ok=True),允许文件夹已存在:
    # 替换原os.mkdir(parent_folder)
    os.makedirs(parent_folder, exist_ok=True)
    
  • truncnorm参数使用错误:原代码对truncnorm.ppf的参数传递不符合要求,该函数前两个参数是标准化后的截断上下限,不是原始数据的范围。假设目标均值为50,标准差为3(可根据需求调整),修改这部分代码:
    a, b = 47.0, 53.0
    mean_r, std_r = 50, 3  # 自定义的均值和标准差
    # 标准化截断上下限
    a_trunc = (a - mean_r) / std_r
    b_trunc = (b - mean_r) / std_r
    # 生成截断正态分布的分位数
    r = (1e-6) * truncnorm.ppf(np.linspace(0.001, 1.0, Nodes), a_trunc, b_trunc, loc=mean_r, scale=std_r)
    
  • 依赖缺失:若报错提示ImportError,则在运行脚本的Python环境中执行pip install scipy numpy安装依赖库。
  • 路径权限问题:OneDrive目录可能存在权限限制,可将脚本和运行目录移至本地非同步路径测试。

内容的提问来源于stack exchange,提问作者user19977266

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:50:29