如何调用python3的方法.python2中的X脚本.x脚本



我有两个脚本一个在python2。另一个是python3.x我必须调用python3内部的一个方法。从python2内部获取X。x脚本。

这是我到目前为止所尝试的:

python2。X文件:

方法1:
class ServiceOne:
#constructor
#more methods
def process(self):
cmd = ["/home/user/.pyenv/shims/python3.9", "-c", "import logging; 
from python3file import ServiceTwo; service = ServiceTwo(%r,logging);
service.mymethod()" % repr(self)]
try:
subprocess.call(cmd)
except subprocess.CalledProcessError as e:
print("Error occurred while running the subprocess : %s" %str(e))
return True
方法二:
class ServiceOne:
#constructor
#more methods
def process(self):
pickled_self = pickle.dumps(self)
cmd = ["/home/user/.pyenv/shims/python3.9", "-c", "import logging;
import pickle; from python3file import ServiceTwo; 
unpickled_self = pickle.loads(sys.argv[1]); 
service = ServiceTwo(unpickled_self,logging);
service.mymethod()" % pickled_self]
try:
subprocess.call(cmd)
except subprocess.CalledProcessError as e:
print("Error occurred while running the subprocess : %s" %str(e))
return True

我的python3代码是这样的:

class ServiceTwo:
def __init__(self, params, logging):
#doing some stuff
def mymethod(self):
#doing more stuff

Method1抛出语法错误,这是正确的。Method2抛出类似can't pickle file objectscan't pickle instancemethod objects的错误

如何在这里正确地传递self实例。

你不能像那样序列化整个类实例,只是传递你需要从头开始创建ServiceTwo对象的参数。如果有很多参数,将它们转储到json文件中。