8: Importing A File(Command line Python scripting)

本文介绍如何在Python中创建一个名为utils.py的文件,该文件包含一个简单的打印消息函数。然后展示了如何从另一个名为script.py的文件中导入并使用这个函数。这种模块化的编程方式有助于大型项目的组织与管理。

One of the great things about Python is that we can import functions from one package into a file. We can also import functions and classes from one file into another file. This gives us a powerful way to structure larger projects without having to put everything into one file.

We'll experiment with this style of import by writing a function in a file, and then importing it from another file.

If there's a file named utils.py, we can import it from another file in the same directory usingimport utils. All the functions and classes defined in utils.py will then be available using dot notation. If there's a function calledkeep_time in utils.py, we can access it withutils.keep_time() after importing it.

Instructions

Create a file called utils.py that contains the following code:

def print_message():
    print("Hello from another file!")

Modify the original script.py file to instead contain this code:

import utils

if __name__ == "__main__":
    utils.print_message()

Both script.py and utils.py should be in the same folder.

Finally, run python script.py to print out the message

~$ echo -e 'def print_message():\n print("Hello from another file!")' > utils.py~$ echo -e 'import utils\n\nif __name__ == "__main__":\n utils.print_message()' > script.py~$ python script.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值