将值从一个脚本返回到另一个脚本

Sna*_*xib 3 python

我有以下脚本将在目录中运行每个脚本(顺序):

import os

directory = []

for dirpath, dirnames, filenames in os.walk("path\to\scripts"):
    for filename in [f for f in filenames if f.endswith(".py")]:
        directory.append(os.path.join(dirpath, filename))
for entry in directory:
    execfile(entry)
    print x
Run Code Online (Sandbox Code Playgroud)

我的脚本看起来像这样:

def script1():
    x = "script 1 ran"
    return x

script1()
Run Code Online (Sandbox Code Playgroud)

print x被调用时,它说,X没有定义.我只是好奇是否有办法返回值,以便父脚本可以访问数据.

S.L*_*ott 7

我只是好奇是否有办法返回值,以便父脚本可以访问数据.

这就是定义函数和返回值的原因.

脚本1应该包含一个函数.

def main():
    all the various bits of script 1 except the import 
    return x

if __name__ == "__main__":
    x= main()
    print( x )
Run Code Online (Sandbox Code Playgroud)

与您的相同,但现在可以在其他地方使用

脚本2执行此操作.

import script1
print script1.main()
Run Code Online (Sandbox Code Playgroud)

这就是一个脚本使用另一个脚本的方式.