从一个 python 脚本返回值到另一个 [英] return value from one python script to another

查看:70
本文介绍了从一个 python 脚本返回值到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件:script1.py 和 script2.py.我需要从script1.py 调用script2.py 并将script2.py 中的值返回给script1.py.但问题是 script1.py 实际上通过 os 运行 script2.py.

script1.py:

导入操作系统打印(os.system(script2.py 34"))

script2.py

导入系统定义主():x="Hello World"+str(sys.argv[1])返回 x如果 __name__ == "__main__":x= 主()

如您所见,我能够将值放入 script2,但不能返回到 script1.我怎样才能做到这一点?注意:script2.py 必须像命令行执行一样被调用.这就是我使用操作系统的原因.

解决方案

好的,如果我理解正确,你想:

  • 将参数传递给另一个脚本
  • 将另一个脚本的输出检索到原始调用者

我会推荐使用子进程模块.最简单的方法是使用 check_output() 函数.><块引用>

使用参数运行命令并将其输出作为字节字符串返回.

示例解决方案:

script1.py

导入系统导入子流程s2_out = subprocess.check_output([sys.executable, "script2.py", "34"])打印 s2_out

script2.py:

导入系统定义主(参数):打印(你好世界"+arg)如果 __name__ == "__main__":主要(sys.argv [1])

I have two files: script1.py and script2.py. I need to invoke script2.py from script1.py and return the value from script2.py back to script1.py. But the catch is script1.py actually runs script2.py through os.

script1.py:

import os
print(os.system("script2.py 34"))

script2.py

import sys
def main():
    x="Hello World"+str(sys.argv[1])
    return x

if __name__ == "__main__":
    x= main()

As you can see, I am able to get the value into script2, but not back to script1. How can I do that? NOTE: script2.py HAS to be called as if its a commandline execution. Thats why I am using os.

解决方案

Ok, if I understand you correctly you want to:

  • pass an argument to another script
  • retrieve an output from another script to original caller

I'll recommend using subprocess module. Easiest way would be to use check_output() function.

Run command with arguments and return its output as a byte string.

Sample solution:

script1.py

import sys
import subprocess
s2_out = subprocess.check_output([sys.executable, "script2.py", "34"])
print s2_out

script2.py:

import sys
def main(arg):
    print("Hello World"+arg)

if __name__ == "__main__":
    main(sys.argv[1])

这篇关于从一个 python 脚本返回值到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆