Executing Multi-Line Commands in a One-Line Command Line
When using Python's -c option to execute a one-line loop, importing a module before the loop can result in a syntax error. This issue arises because the command line treats the entire command as a single line of code.
To overcome this limitation, there are several approaches:
Using Echo:
<code class="bash">echo -e "import sys\nfor r in range(10): print 'rob'" | python</code>
This command uses echo to insert line breaks into the command string, which Python then interprets as multiple lines.
Using Exec:
<code class="bash">python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"</code>
This approach uses the exec function to dynamically execute a string as Python code.
Using Subshells:
<code class="bash">(echo "import sys" ; echo "for r in range(10): print 'rob'") | python</code>
This command splits the command into multiple lines using subshells. Each line is then executed independently.
Using Crast's Answer:
<code class="bash">python3 -c "import sys ; for r in range(10) : print('rob')"</code>
This approach adds a semicolon before the for loop to indicate that the import statement is a separate command.
Using SilentGhost's Answer:
<code class="bash">python3 -c "import sys ; x = [print('rob') for r in range(10)][0]"</code>
This approach uses Python's list comprehension syntax to execute the loop and assign the first result to x.
Atas ialah kandungan terperinci Bagaimana untuk Melaksanakan Perintah Berbilang Baris dalam Baris Perintah Satu Baris?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!