简体   繁体   English

如何在 xonsh shell 中将 Python 构造的输出通过管道传输到另一个命令?

[英]How to pipe In the xonsh shell the output of a Python construct to another command?

In the xonsh shell how can I pipe the output of a Python construct to another command?xonsh shell 中,如何将 Python 构造的输出通过管道传输到另一个命令? Desired example:想要的例子:

for v in ${...}: print ("{}={}".format(v,${v})) | head

In this for v in ... is the Python construct and head is the command I want to pipe its output through.在这个for v in ...是 Python 构造, head是我想通过管道传输其输出的命令。

The command line above does not work;上面的命令行不起作用; I get always the following error:我总是收到以下错误:

NameError: name 'head' is not defined

Looks like xonsh doesn't leave the Python-mode for the pipe symbol (see "Pipes" in the xonsh docs ).看起来xonsh没有为管道符号保留 Python 模式(请参阅xonsh 文档中的“管道” )。 - So, how can I instruct xonsh to understand the pipe character here as a subprocess-mode symbol? - 那么,如何指示xonsh将此处的管道字符理解为子xonsh模式符号?

Xonsh cannot support piping arbitrary Python code to subprocesses, because subprocesses only accept string inputs. Xonsh 不支持将任意 Python 代码通过管道传输到子进程,因为子进程只接受字符串输入。 Therefore xonsh only accepts Python expressions that are strings, contain strings (eg lists of strs), or return strings (eg functions).因此,xonsh 只接受字符串、包含字符串(例如字符串列表)或返回字符串(例如函数)的 Python 表达式。 The reason that xonsh only accepts expressions for subprocesses is that the subprocess itself is implemented as an expression. xonsh 只接受子进程的表达式的原因是子进程本身是作为表达式实现的。

The problem with the example code above is that you are attempting to pipe a statement (a for-statement, specifically) into a subprocess (which is an expression).上面示例代码的问题在于您试图将语句(特别是 for 语句)通过管道传输到子进程(即表达式)中。 This is not syntactically valid in pure Python and isn't in xonsh because it is not clear which of the statements in |这在纯 Python 中在语法上无效,在 xonsh 中也不有效,因为不清楚|哪些语句。 the expression after the | |后面的表达式should be applied to.应该适用于。

To fix the above, you need to change the for-loop to be an expression.要解决上述问题,您需要将 for 循环更改为表达式。 Here are a couple of examples how:以下是几个示例:

# use a list comprehension
echo @(["{}={}\n".format(v,${v}) for v in ${...}]) | head

# use a function
def f(): 
    for v in ${...}: 
        print("{}={}".format(v,${v}))

@(f) | head

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

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