how to pass string containing newline to python in php
<p>I have the following line of code in php that I m using to execute the python screen. and it takes in text from a html textarea which will contain newline characters</p>

<pre><code>$string = $_POST['textarea']; // e.g. "String 1\n string 2\n"
$command = escapeshellcmd("python script.py -c \"$string\"");
</code></pre>

<p>when the script.py is executed, only "String 1" is received by the python script as arg. May I ask is there any native way for me to get the string passed?</p>

<p>If you feel that this is a duplicated question, please let me know where I can find this answer. I have been searching it all over stackoverflow.</p>

<p>I have managed to find a way to do this.</p>

<p>In the php file, replace all the newline with '\n' before calling escapeshellcmd</p>

<pre><code>$string = trim(preg_replace('/[\r\n]+/', '\n', $_POST['textarea']));

// For a string like:
// abcd
// defg
// will become
// abde\\ndefg
</code></pre>

<p>Since the newline char '\n' has been escaped by php escapeshellcmd with the prepended slash. the shell will be able to process the string and python will receive <strong>abde\ndefg</strong> as one of the arguments.
Next in the python code, we simply have to undo the escape using the code below</p>

<pre><code>arg = sys.argv[1].decode('string_escape')
</code></pre>

<p>I hope the above solution will be able to help those who are facing the similar issue as me. =)</p>

php python