请将下列shell语句转换为python语句:while true; do [ -z "${1:-}" ] && break; case "$1" in --help|-h) if [ -z "$help_message" ]; then echo "No help found." 1>&2; else printf "$help_message\n" 1>&2 ; fi; exit 0 ;; --*=*) echo "$0: options to scripts must be of the form --name value, got '$1'" exit 1 ;; --*) name=`echo "$1" | sed s/^--// | sed s/-/_/g`; eval '[ -z "${'$name'+xxx}" ]' && echo "$0: invalid option $1" 1>&2 && exit 1; oldval="`eval echo \\$$name`"; if [ "$oldval" == "true" ] || [ "$oldval" == "false" ]; then was_bool=true; else was_bool=false; fi eval $name=\"$2\"; if $was_bool && [[ "$2" != "true" && "$2" != "false" ]]; then echo "$0: expected \"true\" or \"false\": $1 $2" 1>&2 exit 1; fi shift 2; ;; *) break; esac done
时间: 2024-03-19 09:44:58 浏览: 90
以下是将shell语句转换成Python语句的示例代码:
```python
import sys
import re
while True:
if len(sys.argv) < 2:
break
arg = sys.argv[1]
if arg in ["--help", "-h"]:
if help_message is None:
print("No help found.", file=sys.stderr)
else:
print(help_message, file=sys.stderr)
sys.exit(0)
elif re.match(r'--\*=.*', arg):
print(f"{sys.argv[0]}: options to scripts must be of the form --name value, got '{arg}'", file=sys.stderr)
sys.exit(1)
elif re.match(r'--.*', arg):
name = arg[2:].replace("-", "_")
if name not in globals():
print(f"{sys.argv[0]}: invalid option {arg}", file=sys.stderr)
sys.exit(1)
oldval = globals()[name]
was_bool = isinstance(oldval, bool)
if was_bool and arg == "--" + name and len(sys.argv) > 2 and sys.argv[2] in ["true", "false"]:
val = sys.argv[2] == "true"
del sys.argv[2]
sys.argv[1] = "--" + name
elif was_bool and arg == "--" + name:
val = not oldval
elif len(sys.argv) > 2:
val = sys.argv[2]
del sys.argv[2]
sys.argv[1] = "--" + name
else:
print(f"{sys.argv[0]}: expected value after {arg}", file=sys.stderr)
sys.exit(1)
if was_bool and not isinstance(val, bool):
print(f"{sys.argv[0]}: expected 'true' or 'false': {arg} {val}", file=sys.stderr)
sys.exit(1)
globals()[name] = val
else:
break
```
请注意,在Python中,变量名不能包含连字符,因此我们将所有连字符替换为下划线。另外,我们使用Python的内置正则表达式模块`re`来匹配参数。
此代码假定您已经将命令行参数传递给脚本,并且在Python中,您可以使用全局`globals()`函数来访问全局变量。
阅读全文