简体   繁体   中英

how to display content of variables of file1 to file2 in python

i want to display content of list of file1 to file 2 in python

I am just providing a sample code in that file1 have a list and a variable. I just wanted to display content of that list in file2 by importing. the code is giving an error

from file1 import list1,p

ImportError: cannot import name list1

my code is :

file1:

if __name__ == '__main__':
    list1 = ['a','b']
    p = 123
    print list1
    print p

file2:

from file1 import list1,p
if __name__ == '__main__':
    list2 = ['p','q']
    pb = 321
    print list2
    print pb
    print list1
    print p

in file1 you have if __name__ == '__main__': but since file1 is imported, that's not true in this case. Perhaps something like this for file would be more appropriate:

list1 = ['a','b']
p = 123
if __name__ == '__main__':
    print list1
    print p

It seems that in your case the print statements are only there for debugging in the case that file1 is invoked directly. But list1 and p must be defined to be imported, in which case the print statements probably aren't supposed to run (I'd assume from your code).

Just remove the if statement:

file1.py:

list1 = ['a','b']
p = 123

file2.py:

from file1 import list1,p
print(list1) #output: ['a', 'b']

I would make your list1 and p functions instead of just variables (see below):

file1.py

if __name__ == '__main__':
    list1 = ['a','b']
    p = 123
    print(list1)
    print(p)

def list1():
    list1 = ['a','b']
    print(list1)

def p():
    p = 123
    print(p)

And then in your second file call them like so:

file2.py

from file1 import *
if __name__ == '__main__':
    list2 = ['p','q']
    pb = 321
    print(list2)
    print(pb)
    list1()
    p()

You could also more simply just do this instead:

list1 = ['a','b']
p = 123
if __name__ == '__main__':
    print(list1)
    print(p)

Hope this helps!

In file1, instead of having if __name__ == '__main__' you should use if __name__ == 'file1' . This is because when you are importing this file in file2, the __name__ of file1 is not __main__ instead it is the name of the file which is file1 .

So, having something like this will help:

file1:

if __name__ == 'file1':
    list1 = ['a','b']
    p = 123
    print(list1)
    print(p)

file2:

from file1 import list1,p
if __name__ == '__main__':
    list2 = ['p','q']
    pb = 321
    print(list2)
    print(pb)
    print(list1)
    print(p)

Output, when running file2:

['a', 'b']
123
['p', 'q']
321
['a', 'b']
123

You can remove the brackets from the print statements as I am using Python3 instead of Python2.

But using __name__ == 'file1' is redundant in file1.

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