繁体   English   中英

如何从IDLE中的.py文件单独运行Python脚本的选择性部分

[英]How to run a selective part of the Python script individually from .py file in IDLE

我刚刚开始使用Python,最近我想到了一个问题。 当我使用Python脚本保存代码并运行代码时,直接从脚本开始,它将始终在脚本中运行整个代码。 我想知道是否还有其他选择,我只能在其中运行代码的一部分。 假设我们有以下代码,并且我想运行代码直到打印位于第六行的thisdict 但是,当我尝试从IDLE脚本中运行此代码时,它将运行整个代码。 因此,请让我知道是否还有其他解决方案可以运行整个脚本中的选择性代码。

thisdict={
"brand" : "Ford",
"model" : "Mustang",
"year" : 1964
}
print thisdict
#Tracing the model using the index/key named "model"
print "Model of the car:", thisdict.get("model")
#Changing the "year" to 2018 and re-printing the dictionary
thisdict["year"]=2018
print thisdict 
#Print both keys and values from the dictionar
for x,y in thisdict.items():
print x,y
#Add a key and value to the dictionary

thisdict["color"]="red"
print thisdict

#To delete a keyword from the dictionary
del thisdict["color"]
print thisdict
#OR
thisdict.pop("model")
print thisdict

 #To remove the last item from the dictionary
thisdict.popitem()
print thisdict

#Dist constructore for creating a dictionary
thisdict=dict(brand="Ford",model="Mustang", year=1964)
print thisdict

在几乎所有IDE中,您都可以设置断点,在调试模式下,执行将在每个断点处暂停。

您已经提到了IDLE并标记了Xcode,所以我不确定您使用的是哪个,但是此链接包含一个使用IDLE中的断点进行调试的教程。 是针对Xcode的(不使用Python)。

对于Python初学者来说,这是一个奇怪的普遍问题! 有很多修复程序。

首先,最明显的是只注释掉您不想运行的所有内容。 只要在您不想运行的任何行之前加上“#”,它就不会运行。 大多数编辑器允许您一次自动注释掉整个块。

第二种方法(更好的做法)是开始使用函数。 假设您有以下代码:

print("HERE 1")
print("HERE 2")

有时您想同时运行两条线,但有时您只想运行其中一条。 然后尝试将它们置于不同的功能中。

def print_1():
    print("HERE 1")

def print_2():
    print("HERE 2")

现在,您只需要输入命令(不带缩进),即可调用所需的函数:

print_1()

您可以在函数下放置任意多的代码。 也是仅供参考,这对您可能并不重要,但是要知道,直接运行脚本时调用函数的最佳方法是这样的:

if __name__=="__main__":
    print_1()

但是,您现在可以只编写print_1(),而无需if名称是主要内容。 如果您开始从其他地方导入模块,则将是相关的。

然后,您也可以使用第三个技巧,有时我仍然在复杂的情况下执行此操作,即我不知道控制权在哪里,只想杀死程序,是这样的:

import sys
sys.exit(0)

它将停止程序在任何地方运行。

另一种选择是在代码的顶部使用布尔值。

whole_program = True # or False 

print("here 1")
a = 1+3
print("here 2")
if whole_program:
    print("here 3")
    print("something else")
else:
    pass

如果您只是编写脚本,则另一个选择是使用Jupter笔记本,它非常适合隔离要运行的代码部分。

哦,当然,Python是一种解释语言。 因此,您总是可以一次直接在控制台中一次运行一个命令!

最终,您应该开始学习使用函数,然后学习类,因为这些是控制程序流所需要使用的基本结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM