How do I import my user-defined function without h

2019-08-04 18:51发布

问题:

To solve the problem of the (Python) IDLE not having a built-in "clear" function, I created a user-defined function [cls()], that I have stored in a functions.py file in my sys.path.

import sys, functions

My user-defined function works, but I do not prefer always typing in:

functions.cls()

Amendment after Terry's comment

How do I reference my functions.py file with my environmental variable IDLESTARTUP? I have tried the aforementioned by editing my .bash_profile with: $IDLESTARTUP="/Users/Mac/Documents/functions.py" export $IDLESTARTUP and starting up my IDLE using the command with the appropriate flag (idle3.6 -s). [Note: comment image added above in the original question, for reference] []1

How can I make it so I only have to type in my user-defined function, and not my .py file name?

cls()

回答1:

From the beginning of section 3 of the IDLE doc, available both online and as Help => IDLE Help. "Upon startup with the -s option, IDLE will execute the file referenced by the environment variables IDLESTARTUP or PYTHONSTARTUP. IDLE first checks for IDLESTARTUP; if IDLESTARTUP is present the file referenced is run. If IDLESTARTUP is not present, IDLE checks for PYTHONSTARTUP. Files referenced by these environment variables are convenient places to store functions that are used frequently from the IDLE shell, or for executing import statements to import common modules."

In addition, -r file will run the file.

Currently, the startup files are not rerun when one restarts the Shell.



回答2:

You should be able to import cls this way:

from functions import cls

Then you can call the method this way:

cls()



标签: python-idle