使用 shell 脚本运行具有多个参数的程序

Kat*_*ine 4 command-line osx shell shell-script

我有一个 python 程序,我通过命令行(Mac OSX)运行它:

python -W ignore Experiment.py --iterations 10

该文件Experiment.py应使用不同的值运行多次--iterations。我一次又一次地手动执行此操作,因此当一次运行完成后,我会使用不同的 运行第二次运行--iterations,依此类推。但是,我不能总是靠近我的笔记本电脑来运行所有这些程序,所以我想知道是否有一种方法shell script可以一起声明所有运行,然后 shell 脚本一个接一个地执行它们(不是并行的,只是按顺序执行,就像我我会自己做吗)?就像是:

python -W ignore Experiment.py --iterations 10
python -W ignore Experiment.py --iterations 100
python -W ignore Experiment.py --iterations 1000
python -W ignore Experiment.py --iterations 10000
python -W ignore Experiment.py --iterations 100000
Run Code Online (Sandbox Code Playgroud)

编辑: 如果我有多个参数怎么办--X --Y --Z

And*_*ton 5

您可以使用 for 循环:

for iteration in 10 100 1000 10000 100000; do
    python -W ignore Experiment.py --iteration "${iteration}"
done
Run Code Online (Sandbox Code Playgroud)

如果您有多个参数,并且想要所有参数的所有各种排列,如@Fox 在下面的评论中指出的那样,您可以使用嵌套循环。例如,假设您有一个--name参数,其值可以是n1n2n3,那么您可以执行以下操作:

for iteration in 10 100 1000 10000 100000; do
    for name in n1 n2 n3; do
         python -W -ignore Experiment.py --iteration "${iteration}" --name "${name}"
    done
done
Run Code Online (Sandbox Code Playgroud)

例如,您可以将其放入文件中,runExperiment.sh并将其作为第一行:#!/bin/bash。然后您可以使用以下任一方法运行脚本:

bash runExperimen.sh
Run Code Online (Sandbox Code Playgroud)

或者,您可以使脚本可执行,然后运行它:

chmod +x runExperiment.sh
./runExperiment.sh
Run Code Online (Sandbox Code Playgroud)

如果您先对某些结果感兴趣,这将指导您如何构建循环。在上面的示例中,脚本将运行:

... --iteration 10 --name n1
... --iteration 10 --name n2
... --iteration 10 --name n3
... --iteration 100 --name n1
Run Code Online (Sandbox Code Playgroud)

因此,它会运行第 10 次迭代的所有实验,然后再进行下一次迭代。相反,如果您希望n1在进行下一个实验之前对名称进行所有实验,则可以将名称循环设置为“外”循环。

for name in ...; do
    for iteration in ...; do
Run Code Online (Sandbox Code Playgroud)