1

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 ?

san45
  • 459
  • 1
  • 6
  • 15

3 Answers3

1

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.

ProfHase85
  • 11,763
  • 7
  • 48
  • 66
1

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.

Community
  • 1
  • 1
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
0

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.

Corley Brigman
  • 11,633
  • 5
  • 33
  • 40
  • what if i need the value from local block ?.After doing as above am getting null value as user in correlationSvg.py – san45 Mar 05 '14 at 22:27
  • like others have said, `__name__` will only be `__main__` if this is the entry module, i.e. `c:\python26\python.exe emotion.py`. that's not what you want. when you import a module, _all_ its code is executed immediately (though usually, that 'code' just declares a function). If you want the user prompt to be done all the time, don't hide it behind a name check, just include it. You could also make it a function that does the user entry and returns the string; you would then just call the function. – Corley Brigman Mar 06 '14 at 05:23