The command
JavaScript
x
2
1
python -c "print('hello')"
2
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
JavaScript
1
3
1
python -c "for i in range(10): if i % 2 == 0: print('hello')"
2
python -c "for i in range(10):n if i % 2 == 0:n print('hello')"
3
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 "..."')
.
Advertisement
Answer
You can use bash’s $'foo'
string syntax to get newlines:
JavaScript
1
2
1
python -c $'for i in range(10):n if i % 2 == 0:n print("hello")'
2
(I’m using single space indents here)
For windows, you really should be using powershell, which has `n
as a newline:
JavaScript
1
2
1
python -c "for i in range(10):`n if i % 2 == 0:`n print('hello')"
2
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.