简体   繁体   中英

Importing and storing the data from a Python file

How do I import a Python file and use the user input later?

For example:

#mainprogram
from folder import startup
name

#startup
name = input('Choose your name')

What I want is to use the startup program to input the name, then be able to use the name later in the main program.

您可以稍后在代码中通过startup.name访问该变量。

name will be in startup.name . You can use dir(startup) to see it.

Or, as an alternate solution:

# Assuming from the names that 'folder' is a folder and 'startup' is a Python script
from folder.startup import *

now you can just use name without the startup. in front of it.

I think is better do your code in classes and functions. I suggest you to do:

class Startup(object):
@staticmethod
def getName():
    name = ""
    try:
        name = input("Put your name: ")
        print('Name took.')
        return True
    except:
        "Can't get name."
        return False

>> import startup
>> Startup.getName()

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