【问题标题】:How to store the output of a python script in a variable如何将python脚本的输出存储在变量中
【发布时间】:2019-07-05 10:10:27
【问题描述】:

我有一个 python 脚本“script1.py”,它在执行结束时创建一个字典“out_dict”。我正在从另一个脚本“script2.py”调用“script1.py”。

有没有办法只将最终字典“out_dict”(注意:我在“scirpt1.py”中也有一些打印语句)放入“script2.py”中的变量中。

script1.py

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

script2.py

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

【问题讨论】:

  • 你能打印输出吗?
  • 您可以在print(out_dict) 之前插入print("MARKER") 之类的内容,然后在此标记字符串上拆分val,并仅使用拆分的第二个字段。鉴于这两个脚本都在 Python 中,将一个导入另一个然后直接传递字典不是更容易/更好吗?

标签: python


【解决方案1】:

script1.py开头添加

import pickle as p

在你的字典创建后添加

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

然后在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

您根本无法将您的 dict 保存到文件中,而只能像类 var 一样从 script1.py 访问它,但您必须导入您的第一个脚本。

script2.py 示例:

import script1

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

【讨论】:

    【解决方案2】:

    您需要声明 2 个文件。第一个将包含您要调用的函数。像这样:

    func.py

    def myFunc():
        return 2
    

    在脚本中你要调用的函数你必须这样做:

    ma​​in_script.py

    import func
    
    val = func.myFunc()
    print(val)
    

    【讨论】:

      【解决方案3】:

      两种方法:

      1. 将输出字典存储在另一个文件中,然后由 script2.py 读取
      2. 按照 Daniel 的建议,使用记号笔。它会减轻另一个文件的负担,但您需要一个合适的标记。

      【讨论】:

        【解决方案4】:

        更简单的方法是将一个文件导入另一个文件并使用该字典

        func.py

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

        ma​​in.py

        import func
        val = func.function()
        

        【讨论】:

          猜你喜欢
          • 2021-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-21
          • 1970-01-01
          • 2012-04-03
          • 2021-12-11
          相关资源
          最近更新 更多