简体   繁体   中英

Execute python file from another python script, failed if python file has nested function

I'm creating a python script to do I2C read and write. The script also handles test scripts (also in python) to send hardware. The test scripts previously are sent through GUI, but my script by-passes GUI usage and talks to I2C driver directly. If the test scripts are flat, no problem. However, if there's nested function or global variable, there's error:

def main():
    board=usb2any()
    board.ReadI2C(0x58,0x0)
    board.WriteI2C(0x58,0xBC,0x40)
    execfile(f1)
if __name__ == "__main__":
    main()

The test code "f1", if it only contains codes like below, it runs fine

board.ReadI2C(0x58,0x2)
board.WriteI2C(0x58,0x20,0x10)

however if it looks like this: test script example 1

V1=0
def fun1():
    if V1==1: # error here saying global variable V1 not defined

Another example of failed case: test script example 2

ff(0x10,0x9)
def ff(v1,v2):
    fun2(v1)   #Error here saying fun2 not defined

def fun2(vv): vv=0

Any idea how to solve this? prefer not touching test scripts because those have been used with GUI.

Example 2 doesn't work because you are calling the function before declaring it. Try this instead:

def ff(v1,v2): 
    fun2(v1) 
ff(0x10,0x9)

Example 2 needs some rearranging so you define the functions before calling them. You might want to make a class if you're calling lots of functions from each other.

def fun2(vv): 
    vv=0

def ff(v1,v2): 
    fun2(v1)

`

Here's what's working and what's not: For test script example 1, need to add global in test script global V1 V1=0 def fun1(): if V1==1: #now there's no error

Another example of failed case: test script example 2, which shifting the sequence, still failed

def fun2(x):
    x = 0

def ff(vv):
    fun2(vv)
ff(2) #when calling ff, error saying no fun2 defined

Printout info:

Traceback (most recent call last):

File "c:\\Users\\a0272122\\Documents\\Python Scripts\\I2C_USB2Any\\i2c_wr.py", line 68, in main()

File "c:\\Users\\a0272122\\Documents\\Python Scripts\\I2C_USB2Any\\i2c_wr.py", line 42, in main execfile(file_name)

File "pattern_test.py", line 122, in apb_read_modifywrite (0x1A4, 0x000000E0, 0x00000020)

File "pattern_test.py", line 113, in apb_read_modifywrite read_data = apb_read_reg (addr16b)

NameError: global name 'apb_read_reg' is not defined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM