0

Background:

I'm creating a report that gets sent out to various users in the organization.

I have 3 separate files to do this.

The solution works fine, however it just keeps producing the same file over and over again for the last user in the list.The variable that is being saved is only the last one being executed. It should be producing a different file for each user. I'm not sure if this a nested loop issue, but see below for more context:


File 1) subscribers.py - a list of emails:

subscriber_list = ['abe@gmail.com','obama@gmail.com','clinton@gmail.com']

File 2) start.py - loops through subscribers to execute third file:

import subscribers


for user in subscribers.subscriber_list :
    login_input = user
    exec(open('produce_report.py').read())  

File 3) produce_report.py - runs through a series of logic based on login_input, for simplicity I'm just going to print the value.

import subscribers 
import start


login_input = start.login_input

print (start.login_input)

Expected Result:

  • abe@gmail.com
  • obama@gmail.com
  • clinton@gmail.com

Result I'm getting:

  • clinton@gmail.com
  • clinton@gmail.com
  • clinton@gmail.com
mikelowry
  • 1,307
  • 4
  • 21
  • 43
  • In `start.py` `login_input` gets updated every iteration of the for loop, preserving only the last updated value. – ywbaek May 10 '20 at 01:29
  • 1
    Any reason you aren't using a function in `produce_report` so you can pass info from `start` to the function - making the imports in `produce_report` unnecesary? – wwii May 10 '20 at 01:51
  • Or have `produce_report` rely on command line parameters/arguments and execute it from `start`? – wwii May 10 '20 at 01:55
  • 1
    How are you executing this solution? If I create a fourth .py file with `import start` in it, it seems to work and produce the expected output. – martineau May 10 '20 at 01:55
  • Does this answer your question? [Run a Python script from another Python script, passing in arguments](https://stackoverflow.com/questions/3781851/run-a-python-script-from-another-python-script-passing-in-arguments) – wwii May 10 '20 at 01:55
  • Instead of `import start`, try `import __main__` and then `__main__.login_input` – Luke-zhang-04 May 10 '20 at 02:28
  • @Luke-zhang-04 so that worked... how do I add a fourth file...and carry the variable from the third to the fourth? The `__main__` does not work. – mikelowry May 10 '20 at 03:14

1 Answers1

0

Instead of import start, try import __main__ and then __main__.login_input

import __main__ just imports the executable script, so the fourth file with import __main__ will just import start.py again. Your best bet is to write a function in the fourth file and pass in parameters. To do this you would import your function in produce_report.

There's also another option. Since you are saving the variable in start.py, why don't you carry the variable from start.py to the fourth file?

Luke-zhang-04
  • 782
  • 7
  • 11