How to import input variable from another file without repeated running this input function?

Viewed 47

My master.py asks for participant name and then run other .py files that use this name:

master.py:

participant = str(input("Participant's name: "))

if __name__ == "__main__":
    import os, subprocess
    cDir = os.path.dirname(os.path.realpath(__file__))
    files = ['antisaccade','change_detection','digit_span']
    for f in files:
        wDir = cDir+ '/' + f
        subprocess.run(["python", f+'.py'], cwd=wDir)

For example, digit_span.py:

sys.path.append(os.path.abspath('../'))
from master import participant
filename = u'data/%s_%s_%s' % participant

So each time files are run, they cyclically call line with input:

participant = str(input("Participant's name: "))

But I need to ask for participant's name only once and then send it to other files.

If I put input() inside if, I get the

ImportError: cannot import name 'participant'

Could someone explain how to solve this, please?

1 Answers

If master.py ask for name and run scripts .py which are in the list, what you can do is to pass the name as arguement.

Just like this:

master.py

participant = list([str(input("Participant's name: "))])
if __name__ == "__main__":
    import os, subprocess
    cDir = os.path.dirname(os.path.realpath(__file__))
    files = ['slave']
    for f in files:
        wDir = cDir+ '/' + f
        subprocess.Popen(["python", "{0}.py".format(wDir)]+participant)

slave.py

import sys

with open("check.txt".format(sys.argv[1]),'w') as f:
    f.write("{0} participant".format(sys.argv[1]))

master.py will run slave.py along with the arguments.

To test the result, it will generate a file check.txt with participant's name in it which means that master.py is passing the name to the (slave.py)script.

Related