複数行のコマンドを 1 行のコマンド ラインで実行するにはどうすればよいですか?

Barbara Streisand
リリース: 2024-10-18 11:14:03
オリジナル
276 人が閲覧しました

How to Execute Multi-Line Commands in a One-Line Command Line?

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(\&quot;import sys\nfor r in range(10): print 'rob'\&quot;)&quot;</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 サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!