TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

How to run external programs from Python and capture their output

1 点作者 rayvega超过 10 年前

1 comment

dalke超过 10 年前
I weep! This code is only useful when security and portability are not concerns. Admittedly that&#x27;s the case here, but for more general cases use subprocess for real. Here&#x27;s the code:<p><pre><code> cmd = &#x27;vw --loss_function logistic --cache_file {} -b {} 2&gt;&amp;1&#x27;.format( path_to_cache, b ) output = subprocess.check_output( &#x27;{} | tee &#x2F;dev&#x2F;stderr&#x27;.format( cmd ), shell = True ) </code></pre> What happen if path_to_cache contains a space, or other shell metacharacter? The documentation warns that &#x27;shell = True&#x27; is a security hazard. And this isn&#x27;t portable to a non-Unix OS.<p>A possibly better solution is:<p><pre><code> output = subprocess.check_output( [&quot;vw&quot;, &quot;--loss_function&quot;, &quot;logistic&quot;, &quot;--cache_file&quot;, path_to_cache, &quot;-b&quot;, b,&quot;], stderr = subprocess.STDOUT) </code></pre> This doesn&#x27;t have the tee, which is exists &quot;so [output] gets printed on screen while at the same time it goes to standard output and is captured.&quot;<p>Since that&#x27;s important, another solution is:<p><pre><code> p = subprocess.Popen( [&quot;vw&quot;, &quot;--loss_function&quot;, &quot;logistic&quot;, &quot;--cache_file&quot;, path_to_cache, &quot;-b&quot;, b,&quot;], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) output = [] for line in p.stdout: sys.stderr.write(line) output.append(line) if not p.wait(): raise AssertionError(&quot;There was an error&quot;) </code></pre> I&#x27;m the first to admit that this is longer, which may be an important concern for some. I prefer the greatly reduced number of gotchas.