简体   繁体   English

如何将python脚本的输出存储在变量中

[英]How to store the output of a python script in a variable

I have a python script 'script1.py' which creates a dictionary 'out_dict' at the end of the execution. 我有一个python脚本'script1.py',它在执行结束时创建了一个字典'out_dict'。 I'm calling 'script1.py' from another script 'script2.py'. 我从另一个脚本“ script2.py”调用“ script1.py”。

Is there any way to get only the final dictionary 'out_dict' (note : I have some print statements too in 'scirpt1.py') into a variable in 'script2.py'. 有什么办法只能将最终字典“ out_dict”(注意:“ scirpt1.py”中也有一些打印语句)转换为“ script2.py”中的变量。

script1.py script1.py

......
......
some print statement
......
some print statement
......
out_dict = {...}
print(out_dict)

script2.py script2.py

import os
val = os.system("python3.6 script1.py")

At the start of script1.py add script1.py的开头添加

import pickle as p

and after your dict was created add 在您的字典创建后添加

with open('dict.p', 'wb') ad f:
    p.dump(out_dict, f)

Then in script2.py again import pickle but this time load from a file 然后在script2.py再次导入pickle,但这一次是从文件加载

import os
import pickle as p
val = os.system("python3.6 script1.py")

with open('dict.p', 'rb') as f:
    your_dict = p.load(f)     # your dict will loaded

OR 要么

You can not save your dict into a file at all and just access it from script1.py like a class var, but you will have to import your first script though. 您根本无法将dict保存到文件中,而只能像class var这样从script1.py访问它,但是您将必须导入第一个脚本。

script2.py example: script2.py示例:

import script1

your_dict = script1.out_dict     # your dict var from the first script
print (out_dict)

You need to declare 2 files. 您需要声明2个文件。 The first will contain the function you want to call. 第一个将包含您要调用的函数。 Like this: 像这样:

func.py func.py

def myFunc():
    return 2

In the script you want to call the function you have to do this: 在脚本中,您需要调用该函数:

main_script.py main_script.py

import func

val = func.myFunc()
print(val)

Two ways of doing this: 有两种方法:

  1. Store the output dictionary in another file which is then read by script2.py 将输出字典存储在另一个文件中,然后由script2.py读取
  2. As Daniel suggested, use a marker. 正如丹尼尔(Daniel)建议的那样,使用标记物。 It would remove the burden of another file but you would need an appropriate marker. 这样可以减轻另一个文件的负担,但是您需要一个适当的标记。

Easier method would be to import one file in another and use that dictionary : 更简单的方法是将一个文件导入另一个文件并使用该字典

func.py func.py

def function():
    out_file=dict()
    # Your Code
    return out_file

main.py main.py

import func
val = func.function()

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

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