mut*_*mar 3 python command-line bash scripts
我试图从 shell 脚本返回一个字符串到 python 得到以下错误。
./whiptail.sh: 10: return: Illegal number: uuiiu
Run Code Online (Sandbox Code Playgroud)
我尝试在 python 中直接使用 subprocess.Popen 运行whiptail命令,即使那时我无法从 python 读取用户输入..如果有人尝试过这个,请告诉我如何解决这个问题。
外壳脚本片段
#!/bin/sh
COLOR=$(whiptail --inputbox "What is your favorite Color?" 8 78 Blue --title "Example Dialog" 3>&1 1>&2 2>&3)
# A trick to swap stdout and stderr.
# Again, you can pack this inside if, but it seems really long for some 80-col terminal users.
exitstatus=$?
if [ $exitstatus = 0 ]; then
echo "User selected Ok and entered " $COLOR
return $COLOR
else
echo "User selected Cancel."
fi
echo "(Exit status was $exitstatus)"
Run Code Online (Sandbox Code Playgroud)
在sh这实际上是dash在Ubuntu的内置命令return可以只返回数值-退出状态,其中有一个功能或执行的脚本的上下文中的含义。来源man sh:
返回命令的语法是
Run Code Online (Sandbox Code Playgroud)return [exitstatus]
您的 shell 脚本的其他所有内容看起来都正确。我认为你需要使用echo $COLOR,而不是返回并抑制其他回声-ES。
如果您需要将更多数据返回到主脚本,您可以将所有内容输出为一行,并将单独的字段划分为 一些字符,这些字符将在主脚本中扮演分隔符的角色,您可以在此基础上将字符串转换为数组。例如(,我们的定界符在哪里,-n并将取代 内的换行符echo):
echo -n "$COLOR","$exitstatus"
Run Code Online (Sandbox Code Playgroud)
脚本提供且主脚本不需要的其他信息可以重定向到某个日志文件:
$ cat whiptail.sh
Run Code Online (Sandbox Code Playgroud)
#!/bin/sh
log_file='/tmp/my.log'
COLOR=$(whiptail --inputbox "What is your favorite Color?" 8 78 Blue --title "Example Dialog" 3>&1 1>&2 2>&3)
exitstatus=$?
if [ $exitstatus = 0 ]; then
echo "User selected Ok and entered $COLOR" > "$log_file"
echo -n "$COLOR","$exitstatus"
else
echo "User selected Cancel." >> "$log_file"
echo -n "CANCEL","$exitstatus"
fi
Run Code Online (Sandbox Code Playgroud)
不幸的是,我对 Python 没有太多经验,但这里有一个示例 .py 脚本,可以处理上述 .sh 脚本(参考)的输出:
$ cat main-script.py
Run Code Online (Sandbox Code Playgroud)
return [exitstatus]
Run Code Online (Sandbox Code Playgroud)