子流程中模块的Python调用函数 - python

我想检索从主程序调用的模块函数的stdout,stderr和resultcode。我以为子流程是关键,但是我没有成功将模块功能提交给子流程。

我有的:

#my_module.py
def run(args):
    do stuff
    print this
    return THAT
if name == "__main__":
    args = read_args()
    run(args)

#my_main_script.py
import subprocess as sp
import my_module
p = sp.Popen(my_module.run(args), stdout=sp.PIPE, stderr=sp.PIPE)
out, err = p.communicate()
result = p.resultcode

发生了什么:
显然,子流程模块使用my_module.run()返回的THAT进行了某些操作,从而引发了崩溃:

如果THAT = list_of_lists错误:AttributeError: "sublist" object has no attribute rfind
如果THAT = ["a","b",0]错误:TypeError: execv() arg 2 must contain only strings如果THAT = ["a","b"]错误:OSError: [Errno 2] No such file or directory
因此,子进程显然希望THAT是包含文件路径的列表?

参考方案

您没有以正确的方式使用子流程:

sp.Popen(["./my_module.py", "arg1", "arg2"], stdout=sp.PIPE, stderr=sp.PIPE)

顺便说一句,如果您没有使用sys.exit(retcode)函数正确退出程序,将不会得到任何结果代码。

最终脚本如下所示:

#my_module.py
def run(args):
    do stuff
    print this
    return THAT

if name == "__main__":
    import sys
    args = read_args()
    sys.exit(run(args))

#my_main_script.py
import subprocess as sp

p = sp.Popen(["./my_module.py", "arg1", "arg2"], stdout=sp.PIPE, stderr=sp.PIPE)
out, err = p.communicate()
result = p.returncode

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python:无法识别Pip命令 - python

这是我拍摄的屏幕截图。当我尝试在命令提示符下使用pip时,出现以下错误消息:pip无法识别为内部或外部命令,可操作程序或批处理文件。我已经检查了这个线程:How do I install pip on Windows?我所能找到的就是我必须将"C:\PythonX\Scripts"添加到我的类路径中,其中X代表python版本。如您在我的…

Subprocess.Popen标准输出,等待程序完成 - python

我正在通过subprocess.Popen运行程序,遇到一个意外问题,其中stdout不能实时打印,而是等待程序完成。奇怪的是,这仅在使用Python编写被调用程序时发生。我的控制程序(一个使用子过程的程序)如下:import subprocess import os print("Warming up") pop = subproces…

Python:如何将有效的uuid从String转换为UUID? - python

我收到的数据是 { "name": "Unknown", "parent": "Uncategorized", "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" }, 我需要将uuid从Strin…

Python 3会流行吗? - python

我已经学习了一些Python 2和Python 3,似乎Python 2总体上比Python 3更好。这就是我的问题所在。是否有充分的理由真正切换到python 3? 参考方案 总体上,甚至在大多数细节上,Python3都比Python2更好。关于第三方库, Python 3落后于的唯一区域是。使Python变得如此出色的原因不仅在于它作为一种语言的内在特性…