简体   繁体   English

如何编写运行带有参数重新启动的python程序的bash脚本

[英]How to write a bash script that runs a python program that restarts with parameters

I've written a bash script based on this and this . 我已经基于thisthis编写了一个bash脚本。 The script is: 脚本是:

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

I run it: 我运行它:

./run.sh ‘a’ ‘n’

but in data.py 但在data.py中

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

returns false. 返回false。 How do I pass $1 and $2 to my Python program? 如何将$ 1和$ 2传递给我的Python程序? TIA!!! TIA !!!

EDIT: SOLUTION 编辑:解决方案

Thanks to Jandom and andlrc: I call it: 感谢Jandom和andlrc:我称之为:

./run.sh "a" "n"

and change the script to: 并将脚本更改为:

until python data.py "$@" ; do 

script.sh (make sure it allow execute) script.sh(确保它允许执行)

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

script.py (first param is ./script.sh if run as ./script.sh from terminal), so, 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..

You are sending special quotes to your shell script: 您正在向shell脚本发送特殊引号:

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

Run it with single or double quotes: 用单引号或双引号运行它:

./run.sh "a" "b"

Also remember quotes in your bash script or $1 and $2 will undergo word splitting: 还要记住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

As pointed out before you can use "$@" which will refer to all arguments send to your bash script. 如前所述,可以使用"$@"来引用发送到bash脚本的所有参数。

暂无
暂无

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

相关问题 Python脚本在bash中运行,但不在cron中运行? - Python script runs in bash, but not in cron? 如何将 python 程序插入 bash 脚本? - How to insert a python program into a bash script? 如何在我的 python 脚本中重新启动 main() function? 无论我添加什么输入,程序都会重新启动 - How do I restart the main() function in my python script? The program restarts no matter what input I add 如何将参数传递给将使用bash脚本运行的python脚本? - How to pass parameters to a python script that will be run using a bash script? cron 调用 bash 脚本,该脚本调用“脚本”来运行 python 程序。 bash 脚本的下一行在 script/python 完成之前立即运行 - cron invokes bash script which invokes “script” to run python program. Next line of bash script runs immediately, before script/python completes Python脚本在PyCharm中运行,但不在Git Bash中运行 - Python script runs in PyCharm but not Git Bash 用于执行Python程序的Bash脚本 - Bash script to execute a Python program 使用bash脚本执行python程序 - Execute python program with bash script 我如何让BASH脚本作为进程运行? 那么即使Python脚本被杀死,BASH脚本也会永远运行? - How can i let the BASH script run as process? So that even the Python script is killed the BASH script runs forever? 运行一个PHP脚本,该脚本运行一个运行bash脚本的Python脚本,并挂在bash上 - Running a PHP script that runs a Python script that runs a bash script, hangs on bash
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM