如何在另一个脚本中执行 python 脚本并让它返回列表对象



我有一个脚本test.py,我希望它执行另一个脚本this_other_script.py它将返回一个列表对象。 test.py看起来像:

if __name__ == '__main__':
    someValue = this_other_script
    print(len(someValue))

this_other_script.py看起来像:

if __name__ == '__main__':
    data = [a,b,c,d]
    return(data)

当我运行test.py时,我收到错误 SyntaxError: 'return' outside function .

如果这是由于程序范围,我会认为调用程序可以从它正在调用的程序获得返回值。我不希望this_other_script访问test.py未提供给它的变量的值,所以我不确定为什么会显示此错误。

test.py:

if __name__ == '__main__':
    import this_other_script
    someValue = this_other_script.get_data()
    print(len(someValue))

在this_other_script.py:

def get_data():
    data = [1,2,3,4]
    return(data)

替代答案:

在 test.py

if __name__ == '__main__':
    import this_other_script
    someValue = this_other_script.get_data()
    print(len(someValue))

在this_other_script.py:

def get_data():
    data = [1,2,3,4]
    return(data)

if __name__ == '__main__':
    get_data()

最新更新