san45
san45

Reputation: 459

Cant import variable from one script to another in python

I have two python script

emotion.py

if __name__ == '__main__':

    user=raw_input("Enter your name\n")     

    print("Calling open smile functions.....")

    subprocess.Popen("correlationSvg.py", shell=True)

correlationSvg.py

from emotion import user
import os
import csv

with open('csv/test/'+user+'.csv') as f:
  reader = csv.DictReader(f, delimiter=';')
  rows = list(reader)

i am getting error

ImportError: cannot import name user

why is it so ?

Upvotes: 1

Views: 1059

Answers (3)

ProfHase85
ProfHase85

Reputation: 12173

The variable user is defined inside the if __name__ == '__main__' block. This one is not executed when the import statement is executed.

You can of course define a (script-) global variable

user = ""
if __name__ == '__main__':

    user=raw_input("Enter your name\n")     

    print("Calling open smile functions.....")

    subprocess.Popen("correlationSvg.py", shell=True)

If you would like to get the user while execution, I would either put the line

user=raw_input("Enter your name\n")

into correlation.py or:

in  sympathy.py:

def get_user():
    user=raw_input("Enter your name\n") 

and access this function from correlation.py. Just remember: the import statement happens at the time you call the interpreter, while user assignment happpens at runtime.

Upvotes: 1

Lafexlos
Lafexlos

Reputation: 7735

Because you are using if __name__ == '__main__'. If file is being imported from another module, __name__ will be set to the module's name. Which means, codes in that indentation will only be processed if you run emotion.py.

For detailed explanation about __name__, you might wanna look here.

Upvotes: 1

Corley Brigman
Corley Brigman

Reputation: 12381

You could try this, to force user to be global:

user = ''
if __name__ == '__main__':
    user=raw_input("Enter your name\n")     

However... you should really think about what you are doing here. If you don't expect to set user unless this is the main module - what are you expecting to happen when you import it from another module?

Probably, you should be passing this as a parameter to a function, not trying to import it.

Upvotes: 0

Related Questions