如何编写运行python程序的bash脚本,该程序使用参数重新启动

时间:2016-05-07 15:49:35

标签: python bash parameters

我写了一个基于thisthis的bash脚本。脚本是:

@using (Ajax.BeginForm("UploadHactAssesmentAttachment", "Partner", null, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "OnSuccessAttachment"
}))
{
<div class="row">
    <div class="col-lg-3">
        @Html.Label("key finding Add attachment:")
    </div>
    <div class="col-lg-3">
        @(Html.Kendo().Upload()
           .Name("Files")
        )

    </div>
</div>
    <div class="row">
        <div class="col-lg-3"></div>
        <div class="col-lg-3">

            @Html.Kendo().Button().Name("btnAddattachment").Content("Add").HtmlAttributes(new { style = "width: 20%" })
        </div>
    </div>

我跑了:

#!/bin/bash 
until python data.py $1 $2 ; do
    echo "'data.py' crashed with exit code $?. Restarting..." >> errors.txt
    sleep 1
done

但在data.py中

./run.sh ‘a’ ‘n’

返回false。 如何将$ 1和$ 2传递给我的Python程序? TIA !!!

编辑:解决方案

感谢Jandom和andlrc: 我称之为:

if sys.argv[1] == 'a':

并将脚本更改为:

./run.sh "a" "n"

2 个答案:

答案 0 :(得分:3)

script.sh(确保它允许执行)

#!/bin/sh
python script.py "$@"

script.py(如果从终端运行./script.sh,则第一个参数是./script.sh),所以,script.py:

import sys
print(sys.argv[1:])
# sys.argv[1] == a, sys.argv[2] == b, etc..

答案 1 :(得分:2)

您正在向shell脚本发送特殊引号:

% charinfo ‘’
U+2018 SINGLE TURNED COMMA QUOTATION MARK [Pi]
U+2019 SINGLE COMMA QUOTATION MARK [Pf]

使用单引号或双引号运行它:

./run.sh "a" "b"

还要记住bash脚本或$1$2中的引号会进行分词:

#!/bin/bash
until python data.py "$1" "$2"; do
    echo "'data.py' crashed with exit code $?. Restarting..." >> errors.txt
    sleep 1
done

如前所述,您可以使用"$@"来引用发送到bash脚本的所有参数。