Ask coding questions

← Back to all posts
Is there any way to run this "one-liner" inside a while loop, in one line
h
rafrafraf (305)

Even better if you can get rid of the single semicolon I've had to use to accommodate the program.

We can't use a regular while loop and the with statement at the same time while on the same line due to being incorrect syntax.

Putting the entire thing in square brackets and using an infinite for loop wont work either due to the semicolon and possibly the with statement

Commentshotnewtop
pyelias (1773)

You could move the print(...) if ... else print(...) into a lambda, then call it on input(...) to remove the semicolon. Removing the with statement is harder, but you can do it with this monstrosity I just wrote up:

type(lambda: 1)(type((lambda: 1).__code__)(1, 0, 1, 6, 67, b'y\n|\x00\x83\x00\x01\x00W\x00n\x0c\x01\x00\x01\x00\x01\x00Y\x00n\x02X\x00d\x00S\x00', (None,), (), ("cb",), "", "", 0, b"\xff\xff"),{})(lambda: "replace this part with your code")

EDIT: or this one, which doesn't rely on CPython's implementation details:

(lambda cb, asyncio=__import__("asyncio"): asyncio.get_event_loop().run_until_complete(asyncio.gather(asyncio.coroutine(lambda: (cb(), (e for e in []))[1])(), return_exceptions=True)))(lambda: "replace this")

Or this:

(lambda cb: __import__("concurrent.futures").futures.ThreadPoolExecutor(1).submit(cb).exception())(lambda: "replace this")

Once you've done that, you can just wrap the whole thing in a while loop.

Nemoiscool (46)

It is possible, and there are multiple different ways to do it. The easiest of those would be the exec() function. However, this is not recommended in any type of code. Then again, I wouldn't consider one-liners to be particularly recommended either.

Anyway, if you want to use the exec() function, your code would look something like this:

exec("while True:\nwith (type("tryExcept", (object,), {"enter": (lambda args: None), "exit": (lambda args: True)}))(): cmd = input(import('termcolor').colored(">>>",'blue')); print(import('termcolor').colored('error', 'red')) if False in [(lambda i: True if i in '1234567890+-*/ ' else False)(x) for x in cmd] else print(import('termcolor').colored('= %s' % eval(cmd), 'blue'))")

exec() runs the code inside of the quotation marks, so all you need to do is do a '\n' everywhere that there would be a newline in a multi-line program. This allows any multi-line program to be converted into a one-line program.

So again, it is possible, though I still would not recommend it.