Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python -c "code here" with newlines?

The command

python -c "print('hello')"

runs the code inside the quotes successfully, both in Linux (bash) and Windows (cmd.exe).

But how to pass code with newlines, with python -c?

Example: both

python -c "for i in range(10): if i % 2 == 0: print('hello')"
python -c "for i in range(10):\n    if i % 2 == 0:\n        print('hello')"

fail.


Example use case: I need to send a SSH command (with paramiko) to execute a short Python code on a remote server, so I need to pass one command like
ssh.exec_command('python -c "..."').

like image 577
Basj Avatar asked Sep 16 '26 10:09

Basj


1 Answers

You can use bash's $'foo' string syntax to get newlines:

python -c $'for i in range(10):\n if i % 2 == 0:\n  print("hello")'

(I'm using single space indents here)

For windows, you really should be using powershell, which has `n as a newline:

python -c "for i in range(10):`n if i % 2 == 0:`n  print('hello')"

In cmd.exe, it seems that you can use ^ to escape a newline, however I'm unable to test this currently so you should refer to this question's answers.

like image 154
Aplet123 Avatar answered Sep 19 '26 00:09

Aplet123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!