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.
以上が複数行のコマンドを 1 行のコマンド ラインで実行するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。