如何将stdout重定向到Python中的任意文件?
当从ssh会话中启动长时间运行的Python脚本(例如,Web应用程序)并进行后台处理,并且ssh会话关闭时,应用程序将引发IOError并在尝试写入stdout时失败.我需要找到一种方法来将应用程序和模块输出到文件而不是stdout,以防止由于IOError导致的失败.目前,我使用nohup将输出重定向到一个文件,这就完成了工作,但是我想知道是否有办法在不使用nohup的情况下完成它,出于好奇.
我已经尝试了sys.stdout = open('somefile', 'w'),但这似乎并没有阻止一些外部模块仍然输出到终端(或者sys.stdout = ...线路根本没有发射).我知道它应该使用我测试过的简单脚本,但我还没有时间在Web应用程序上进行测试.
我编写了一个命令行实用程序,它使用getopt来解析命令行中给出的参数.我还希望有一个文件名是一个可选参数,比如它在其他实用程序中,如grep,cut等.所以,我希望它具有以下用法
tool -d character -f integer [filename]
Run Code Online (Sandbox Code Playgroud)
我该如何实施以下内容?
有没有办法用with语句开始一段代码,但是有条件地?
就像是:
if needs_with():
with get_stuff() as gs:
# do nearly the same large block of stuff,
# involving gs or not, depending on needs_with()
Run Code Online (Sandbox Code Playgroud)
为了澄清,一种情况会在with语句中包含一个块,而另一种情况可能是同一个块,但不包含(即,好像它没有缩进)
最初的实验当然会给出压痕错误..
python conditional indentation with-statement conditional-statements
python ×3
arguments ×1
command-line ×1
conditional ×1
file ×1
indentation ×1
stdin ×1
stdout ×1