Search code examples
python-3.xxonsh

List comprehension with xonsh


I am still new to this, but is it possible to execute multiple commands in xonsh using a list-comprehension syntax?

I would expect the following to create five files file00 to file04, but it errors instead:

$ [@(['touch', 'file%02d' % i]) for i in range(5)]
............................ 
xonsh: For full traceback set: $XONSH_SHOW_TRACEBACK = True
  File "<string>", line None
SyntaxError: <xonsh-code>:1:1: ('code: @(',)
[@(['touch', 'file%02d' % i]) for i in range(5)]
 ^

I would expect this to work, because the following works fine:

$ [i for i in range(5)]
[0, 1, 2, 3, 4]

$ @(['touch', 'file%02d' % 3])
$ ls
file03

Solution

  • The way closest to your original code is to use a subprocess:

    [$[touch @('file%02d' % i)] for i in range(5)]

    To explain the need for nesting $[ .. @(:

    • The top-level command is a list-comprehension, so we start in Python-mode;
    • We want to execute a bash command (touch) so we need to enter subprocess-mode with $[ (or $( to capture output);
    • But the argument to that command requires string interpolation with Python, hence Python-mode again with @(.