简体   繁体   English

将 Perl 翻译成 Python:要么死,要么死

[英]Translate Perl to Python: do this or die

I am moving a Perl (of which I have very little knowledge) script to python.我正在将 Perl(我对此知之甚少)脚本移动到 python。

$path = $ENV{ 'SOME_NAME' } || die " SOME_NAME ENV VARIABLE NOT FOUND\n";

I can (hopefully) see what this line does, either set the variable 'path' to the environment variable 'SOME_NAME' or failing that then print an error message to the user.我可以(希望)看到这一行的作用,或者将变量“路径”设置为环境变量“SOME_NAME”,或者失败,然后向用户打印一条错误消息。 (Side note: anyone know how to get a search engine to search for special characters like '||'?) (旁注:有人知道如何让搜索引擎搜索“||”等特殊字符吗?)

I've tried to implement it in a "pythonic" way (Easier to Ask Forgiveness than Permission) using:我尝试使用“pythonic”方式(更容易请求宽恕而不是许可)来实现它:

try:
    path = os.environ['SOME_NAME']
except KeyError,e:
    print "SOME_NAME ENVIRONMENT VARIABLE NOT FOUND\n"
    raise e

but this seems rather cumbersome, especially as I'm doing it for 3 different environment variables.但这似乎相当麻烦,尤其是当我为 3 个不同的环境变量执行此操作时。

Any ideas if there is a better implementation or would you say this is the "pythonic" way to go about it?如果有更好的实现有什么想法,或者你会说这是 go 的“pythonic”方式吗?

Many Thanks非常感谢

try:
    path = os.environ['SOME_NAME']
    var2 = os.environ['VAR2']
    var3 = os.environ['VAR3']
    var4 = os.environ['VAR4']
except KeyError,e:
    print "Not found: ", e

You can put more than one statement into a try block.您可以将多个语句放入 try 块中。

What you have there is actually pretty common idiom, and arguably the preferred pattern.你所拥有的实际上是非常常见的习语,并且可以说是首选模式。 Or you just just let the normal exception pass without printing anything extra.或者你只是让正常的异常通过而不打印任何额外的东西。 Python natively has the same effect. Python原生也有同样的效果。 So,所以,

path = os.environ["SOME_NAME"]

Will just raise a KeyError exception all by itself and the default behavior is to exit on uncaught exceptions.只会自行引发 KeyError 异常,默认行为是退出未捕获的异常。 The traceback will show you what and where.回溯会告诉你什么和在哪里。

However, you can also provide a default value, if that's possible.但是,如果可能,您也可以提供默认值。

path = os.environ.get("SOME_NAME", "/default/value")

This will not raise an error and you may do something sensible as a default action.这不会引发错误,您可能会做一些明智的事情作为默认操作。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM