如何从脚本中的特定步骤开始?

2024-06-16 12:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,它执行10个函数,每个函数都跟在一起,我想让用户能够在一个特定的函数上开始执行脚本。你知道吗

例如:

python main.py --start=function4

脚本只执行function4和流程中的下一个函数。你知道吗

我使用getopt。你知道吗

谢谢你的帮助。你知道吗


Tags: 函数用户py脚本main流程startgetopt
3条回答

你可以用

if __name__=='__main__':
     call_desiredfunction()

例如

def c():
    print 'c'

def b():
    print 'b'
    c()

def a():
    print 'a'
    b()


if __name__=='__main__':
    print 'Stared Execution'
    a()

输出:

Stared Execution
a
b
c

你可以这样做

if start >= 1:
    function1()
if start >= 2:
    function2()
if start >= 3:
    function3()

或者有一个函数列表:

f = [None, function1, function2, function3, ...]
for f in f_list[start:]:
    f()

今天我可以给你一些建议:

使用转到

http://entrian.com/goto/

安装软件包:

$ pip install http://entrian.com/goto/goto-1.0.tar.gz#goto

编写一些代码:

from goto import goto, label

label .getinput
i = raw_input("Enter either 'a', 'b' or 'c', or any other letter to quit: ")
if i in ('a', 'b', 'c'):
    goto *i
else:
    goto .quit

label .a
print "You typed 'a'"

label .b
print "You typed 'b'"

label .c
print "You typed 'c'"

label .quit
print "Finished\n"

然后运行它:

$ python gt.py 
Enter either 'a', 'b' or 'c', or any other letter to quit: b
You typed 'b'
You typed 'c'
Finished

警告:在练习之前,请先查看日历。顺便说一句,代码真的很管用。你知道吗

相关问题 更多 >