How do I import my user-defined function without having to call the .py file it is in?

ぐ巨炮叔叔 提交于 2019-12-11 06:05:20

问题


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()



来源:https://stackoverflow.com/questions/49677593/how-do-i-import-my-user-defined-function-without-having-to-call-the-py-file-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!