如何在另一个python文件中运行python文件?

2024-04-25 10:25:16 发布

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

我有以下几点:

# script_1

from ephem import *
import time, math, commands, sys, os

elements = open('orbital_elements.txt')

# Then does some stuff and takes information from the text file, calculating diff_x, diff_y, diff_z

return diff_x, diff_y, diff_z

我还有第二个剧本。这个脚本将脚本1作为一个模块导入,然后在一个范围内循环,每次都会改变轨道_元素.txt在新文本文件上运行script_1,每次返回diff_x,diff_y,diff_z的新值:

#script_2

from __future__ import division
import numpy as np
import pandas as pd
import os
import script_1

df_input = pd.read_csv("sampling.txt", sep = ",", index_col=False)

def convert(x):
    # Input single row of df_input

    epoch_osculation = '2018 02 22'
    M = x['M']
    AOP = x['AOP']
    LOAN = x['LOAN']
    INCL = x['INCL']
    e = x['e']
    a = x['a']

    text_file = open("orbital_elements.txt", "w")
    text_file.write("Object: 1 ceres\n")
    text_file.write("Epoch of osculation     =  " + str(epoch_osculation) + "\n")
    text_file.write("Mean anomaly            =  " + str(M) + "\n")
    text_file.write("Argument of perihelion  =   " + str(AOP) + "\n")
    text_file.write("Long. of ascending node =   " + str(LOAN) + "\n")
    text_file.write("Inclination             =   " + str(INCL) + "\n")
    text_file.write("Eccentricity            =  " + str(e) + "\n")
    text_file.write("Semimajor axis          =  " + str(a))
    text_file.close()

index = np.arange(len(df_input))
df_output = pd.DataFrame(columns=['x', 'y', 'z'], index = index)

for i in range(len(df_input)):
    # Creates text file for script_2.py
    convert(df_input.iloc[i]) 

    script_1

    # Record data in a table
    #df_output['x'][i] = script_1.diff_x
    #df_output['y'][i] = script_1.diff_y
    #df_output['z'][i] = script_1.diff_z

不幸的是,每次我运行第二个脚本时,它都会返回与文本文件相同的值_元素.txt没有改变。你知道吗

我知道文本文件每次都在更新,因为我已经测试过了。问题似乎出在脚本1中,没有识别出轨道的更新版本_元素.txt每次返回相同的值。你知道吗

我是如何调整它的,以便第一个脚本在导入到scriptè2中时,考虑到轨道的更新版本的_元素.txt?你知道吗


Tags: oftextimporttxt脚本元素dfinput
2条回答

尝试关闭文件。我确实认为这是问题所在。你知道吗

# script_1

from ephem import *
import time, math, commands, sys, os

elements = open('orbital_elements.txt')

# Then does some stuff and takes information from the text file, calculating diff_x, diff_y, diff_z
elements.close()
return diff_x, diff_y, diff_z

脚本\u 1的主体将在导入后立即运行:

from ephem import *
import time, math, commands, sys, os

elements = open('orbital_elements.txt')

# Then does some stuff and takes information from the text file, calculating diff_x, diff_y, diff_z

return diff_x, diff_y, diff_z

因此,上述所有代码立即在以下位置运行:

from __future__ import division
import numpy as np
import pandas as pd
import os
import script_1   # <- This line

您需要将代码放入函数中,并仅在适当时调用它:

from ephem import *
import time, math, commands, sys, os

def main():
    elements = open('orbital_elements.txt')

    # Then does some stuff and takes information from the text file, calculating diff_x, diff_y, diff_z

    return diff_x, diff_y, diff_z

然后在需要时使用script_1.main()。你知道吗

相关问题 更多 >

    热门问题