简体   繁体   中英

is it possible to access variable (local or global) main.py when running imported module function?

eg I have 2 py script, namely main.py and stringhelper.py

Since print(f'{student_{i}_{j}}') cannot be read in IDE if variable student_1_2 exist and if i=1 , j=2 , I want to make a function that can print 'x{a{h}b{i}c{j}z}y' by changing the string to

exce('''temp_s = 'a{}b{}c{}z'.format(h,i,j)''') # where I suppose e.g. h can refer to main.h but cannot
exec('''print('x{}y'.format(f'{temp_s}')'''

In stringhelper.py

import re
def execprintf(s):
    
    
    if s.find('{')<0:
        print(s)
        exec('''print(s)''')
    else:
        # use re to do sth to recongize {...{...{ case
        if conditionA: # {...{...{ case
            print('warning for input s')
        elif conditionB: # ... {...{ case 
            # not finished
            # not writing as I meet some problem for simple '{h}' case below
            pass
        else:
            ss = re.split('{|}',s)
            ss_even = ss[0::2]
            ss_odd = ss[1::2]
            s_wo_args = '{}'.join(ss_even)
            s_args = ', '.join(ss_odd)
            exec('''print(s_wo_args.format('''+s_args+'''))''')

In main.py

from stringhelper.py import execprintf
h = 1
exceprintf('{h}') # NameError: name 'h' is not defined

If I copy the execprintf function into main.py and does not import from stringhelper.py , it can read h and display 1. Is it possible to read the h in stringhelper.py? I need at least exceprintf('a{h}b{i}c{j}d') can run correctly first.

You're making a mistake that's common with beginning programmers, confusing data and code. You write your code before anyone (including yourself) runs a program. The code is not (typically) visible to the application when it's running and shouldn't need to be. When your program is running, a user (yourself or whoever) can enter data and this may change the behaviour of the program, but it never affects the code, nor should the user need to know anything about the code you wrote.

If you need to select a specific value based on some input (file, keyboard, whatever), there are other ways of doing that than picking a variable you know to hold that value by name.

In most cases, using a dictionary is the way to go in Python:

values = {
    'a': 'some value',
    'b': 'some other value'
}

choice = input('Pick a or b (and hit Enter):')
print('You selected:', values[choice])

Here, the initial values are in the code, but of course you could even load values from a file and the program would still work, without the user ever needing to know about or interact with your code.

Also, running code through exec() is rarely the correct solution. This involves your program running code entered by a user, which could be literally anything if you're not careful, and thus presents major security risks, as well as many opportunities for your code to fail.

The main reason beginning programmers feel the need to reach over and grab exec() or eval() is because they confuse what should remain in the code with what the user has access to - once you fix that, you'll find you rarely need to think about exec() and eval() .

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