重新启动程序时发送终端输入数据 (python)
Send terminal input data when restarting a program (python)
我的脚本首先要求从终端输入:
ans = raw_input("Do thing A (1) / Do thing B (2)")
然后运行代码并在出现异常时自行重启。
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
问题是我需要人工再次输入选项,所以我尝试了这个:
def restart_program():
python = sys.executable
os.execl(python, python, '1', * sys.argv)
但是没有用。重启时如何发送选项?
像评论中提到的其他人一样,尝试通过 shell 脚本使用 while 循环 运行 你的 python 脚本,smthng like(第一个 运行 wo cmd 行参数) :
arg=''
while true
do
python restart.py $arg
arg='1'
sleep 1800
done
并在您的 python 代码中检查是否提供了参数:
try:
ans = sys.argv[1]
except IndexError:
ans = raw_input("Do thing A (1) / Do thing B (2)")
您只需要在处理异常引发后退出您的程序,而不是从您的代码中重新启动它。
我的脚本首先要求从终端输入:
ans = raw_input("Do thing A (1) / Do thing B (2)")
然后运行代码并在出现异常时自行重启。
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
问题是我需要人工再次输入选项,所以我尝试了这个:
def restart_program():
python = sys.executable
os.execl(python, python, '1', * sys.argv)
但是没有用。重启时如何发送选项?
像评论中提到的其他人一样,尝试通过 shell 脚本使用 while 循环 运行 你的 python 脚本,smthng like(第一个 运行 wo cmd 行参数) :
arg=''
while true
do
python restart.py $arg
arg='1'
sleep 1800
done
并在您的 python 代码中检查是否提供了参数:
try:
ans = sys.argv[1]
except IndexError:
ans = raw_input("Do thing A (1) / Do thing B (2)")
您只需要在处理异常引发后退出您的程序,而不是从您的代码中重新启动它。