如何运行Python脚本的某些部分?

问题描述 投票:0回答:2

我编写了一个脚本来运行其中包含的所有进程,但我希望能够只运行所需的进程。

我认为我对列表的用法不同于我过去所需要的,但我不太清楚如何去做。

我有四个函数:foo1,foo2,foo3和foo4。我希望能够使用input()函数使用特定数量的用户插入,在python脚本本身内有选择地运行这些函数中的任何一个。代码示例如下所示。

ListAllVSs = requests.get('https://' + LMIP + '/access/listvs', verify=False, auth=MyCreds)

ListVSOutput = ListAllVSs.content.splitlines()

for Line in ListVSOutput:
    if b"<Index>" in Line:
        IndexLines.append(Line)

NumbersList = [int(re.search(br"\d+", Integer).group()) for Integer in IndexLines]

for Number in NumbersList:
    VSIDAndValue = (
    ('vs', str(Number)),
    )
    requests.get('https://' + LMIP + '/access/delvs', params=VSIDAndValue, verify=False, auth=MyCreds)

因此,这与单个函数并不完全相关。

例如,用户应插入“1”运行foo1,“2”运行foo2,“3”运行foo3,“4”运行foo4,“5”运行foo1和foo2等。运行所有可能的组合在功能方面,将有15个可能的输入,任何低于0或大于15的数字都应被视为无效。

我想使用“0”来运行所有四个进程,我认为这可能是由于Python对其列表位置的编号,但如果需要,我可以将其作为“15”。

提前致谢!

python python-3.x
2个回答
3
投票

您可以使用按位运算符来测试不同的进程组合:

def foo1():
    print("foo1()")

def foo2():
    print("foo2()")

def foo3():
    print("foo3()")

def foo4():
    print("foo4()")

def input(n):
    if n & (1 << 0) != 0: # (1 << 0) == 1
        foo1()
    if n & (1 << 1) != 0: # (1 << 1) == 2
        foo2()
    if n & (1 << 2) != 0: # (1 << 2) == 4
        foo3()
    if n & (1 << 3) != 0: # (1 << 3) == 8
        foo4()

在这个例子中,从1到15的所有数字都会给出一些输出。 1将打印“foo1()”4将打印“foo3()”...如果要打印“foo1()”和“foo3()”,则应使用参数5(1 + 4)调用input()

理解这一点的关键是要注意每个函数fooX在基数2中使用以下数字调用:

n = 110 = 00012 - > foo1() n = 210 = 00102 - > foo2() n = 410 = 01002 - > foo3() n = 810 = 10002 - > foo4()

并且它们的总和只是一个比特的布尔or|)操作:

(1 + 4)10 = 00012 | 01002 = 01012 = 510

然后比较一个给定的位是否用&(按位and)运算符设置为1并调用相应的fooX()


1
投票

使用字典,对不起我无法评论你的问题我太新了。

dict_functions = { '1' : foo1, '2' : foo2, '3' : foo3,  '4' : foo4}

user_input = input("What Number foo do you want to run? ")

dict_functions[user_input]()

如果你无法弄明白,你可以给我一些示例代码吗?如果你想限制你的输入Limiting user input to a range in Python,也要赞扬这个家伙

© www.soinside.com 2019 - 2024. All rights reserved.