通过MATLAB调用python程序并每次访问同一个python程序实例

时间:2017-06-09 17:46:10

标签: matlab python-3.x python-multithreading python-multiprocessing

我正在使用系统调用从MATLAB R2014a调用python程序(steppermotor.py)。 我正在使用这些命令从MATLAB调用python -

system('C:\Python33\python C:\PhidgetsPython\steppermotor.py initialize()');

steppermotor.py的主要脚本如下所示:

如果名称 =='主要':

if sys.argv[1] =='initialization()':
    initialization(1)

if re.search('CalibrationMIN',sys.argv[1]):
    val = (re.search(r"[+-]?\d+(?:\.\d+)?",sys.argv[1]).group())

    print(val)
    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)

    if data1["Initialize"] ==1:
        if val >= str(0):
            x = CalibrationMIN(float(val))
            print(x)
            exit(x)
        else:
            print('Enter a positive value as input argument')
            exit(3)
    else:
        print('Stepper is not Initialized')
        exit(1)


if re.search('CalibrationMAX',sys.argv[1]):
    val = (re.search(r"[+-]?\d+(?:\.\d+)?",sys.argv[1]).group())

    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)
    if data1["Initialize"] ==1:
        if val >= str(0):
            x = CalibrationMAX(float(val))
            print(x)
            exit(x)
        else:
            print('Enter a positive value as input argument')
            exit(x)
    else:
        print('Stepper is not Initialized')
        exit(1)


if re.search('SetVelocity',sys.argv[1]):
    val = int(re.search(r'\d+', sys.argv[1]).group())

    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)
    if data1["Initialize"] ==1:
        x = SetVelocity(int(val))
        print(x)
        exit(x)
    else:
        print('Stepper is not Initialized')
        exit(1)

if re.search('SetAcceleration',sys.argv[1]):
    val = int(re.search(r'\d+', sys.argv[1]).group())

    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)
    if data1["Initialize"] ==1:
        x = SetAcceleration(int(val))
        print(x)
        exit(x)
    else:
        print('Stepper is not Initialized')
        exit(1)

if re.search('UserMove',sys.argv[1]):
    val = (re.search(r"[+-]?\d+(?:\.\d+)?",sys.argv[1]).group())

    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)
    maxlimit = data1["MaxChart"]
    minlimit = data1["MinChart"]

    if data1["Initialize"] ==1:
        if data1["Calibrate"] ==1:
            if float(val) <= math.ceil(maxlimit) and float(val) >=  float(minlimit):
                x = UserMove(float(val))
                print(x)
                exit(x)
            else:
                print('Please enter the value within the max limit %d and min limit %d .' % (maxlimit, minlimit) )
                exit(4)
        else:
            print('Calibrate and set Maximum and Minumim limits in centimeters')
            exit(2)
    else:
        print('Stepper is not Initialized')
        exit(1)

if re.search('UnconditionalMove',sys.argv[1]):
    val = (re.search(r"[+-]?\d+(?:\.\d+)?",sys.argv[1]).group())

    initialization(1)
    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)
    if data1["Initialize"] ==1:
        x = UnconditionalMove(float(val))
        print(x)
        exit(x)
    else:
        print('Stepper is not Initialized')
        exit(1)

if sys.argv[1] == 'Closeall()':
    closeall()

if sys.argv[1] == 'Stop()':
    Stop()

steppermotor.py的UserMove()函数如下:

def UserMove(TargetPos):

try:
   # Initilize devices
    initialization(0)

    tem = open("count.pkl",'rb')
    data1 = pickle.load(tem)

    # For the first time reading current position of the from chart from the CalibrationMAX output and then updating current position. 
    currentPosition = data1["Max"]

    # Before move command 
    data1["ChartPreviousPosition"] = currentPosition  

    # Subtract the current position values of the chart to the user input position
    # Diff is the no of cm that motor will move  
    Diff = - float(currentPosition) + TargetPos

    # Convert into motor steps 
    g = Diff*float(840.07140)

    # set current position as start position
    stepper.setCurrentPosition(0, 0)
    encoder.setPosition(0,0)

    print("Motor will now move     %.2f  cm" % Diff)

    # Motor will now move to the target position 
    stepper.setTargetPosition(0, int(g))

    # While currentPosition !=TargetPosition
    while stepper.getCurrentPosition(0) != int(g):
        #I want to break this while loop when Stop() is executed/stopFlag==True

        if stopFlag == True:
            exit(1) #return or break
        else:
            #Update the state of the motor
            curr = stepper.getCurrentPosition(0)
            EncodEnd = encoder.getPosition(0)
            Enco = EncodEnd/4
            chartcurr = 0.001190375*curr
            chartpos = currentPosition + chartcurr
            data1.update({'MotorMovedPosition':curr})
            data1.update({'ChartMovedPosition':chartpos})
            data1.update({'Max':chartpos})
    sleep(0.2)


    # Get the postion of the stepper once it has reached target
    curr = stepper.getCurrentPosition(0)

    # Get Encoder count value, the value is in PPR 
    EncodEnd = encoder.getPosition(0)
    # convert that value into CPR 
    Enco = EncodEnd/4

    IdealEncoderCnt = Diff*39.37847

    #Check if the Encoder counts are as expected
    if abs(abs(IdealEncoderCnt) - abs(Enco)) < 4:
        print("Motor moved as expected")
    elif (abs(IdealEncoderCnt) - abs(Enco)) >=4:
        print("Motor didn't move all the way to the target position")
        return 6
    else:
        print("Motor moved beyond the target position")
        return 6

    return 0

except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Exiting....")
    exit(1)

在steppermotor.py的stop()函数中,我设置 stopFlag = True 。 请注意, stopFlag = False 被定义为全局变量。

我尝试使用steppermotor.py多线程(当调用该参数时,通过creatinf为主脚本中的每个函数创建一个线程),甚至进行多处理。但是当MATLAB使用

进行调用时,它似乎都不起作用
%In the MoveMotor callback function of MATLAB
system('C:\Python33\python C:\PhidgetsPython\steppermotor.py UserMove(50)');

%In the stopMotor callback function of MATLAB
system('C:\Python33\python C:\PhidgetsPython\steppermotor.py Stop())');

我认为当第一次调用仍在执行时,当第二次系统调用是从MATLAB进行的时,会创建一个不同的steppermotor.py实例,并且不会在它们之间共享内存。因此,即使在第二次系统调用期间 stopFlag 设置为 True ,我也无法突破while循环。

我是否错过了一些明显的问题,或者是否有解决此问题的方法?

谢谢!

0 个答案:

没有答案