Maison  >  Article  >  développement back-end  >  Comment exécuter des instructions Python multilignes dans une seule commande de ligne de commande ?

Comment exécuter des instructions Python multilignes dans une seule commande de ligne de commande ?

Linda Hamilton
Linda Hamiltonoriginal
2024-10-18 10:38:29822parcourir

How to Execute Multi-Line Python Statements in a Single Command-Line Command?

Executing Multi-Line Python Statements in a Single Command-Line Command

The Python -c option allows for one-liner loop execution, but importing modules within the command can lead to syntax errors. To address this, consider the following solutions:

  • Using Echo and Pipes:
<code class="bash">echo -e "import sys\nfor r in range(10): print 'rob'" | python</code>
  • Using exec() Within -c:
<code class="bash">python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"</code>
  • Using Multiple Echo Commands:
<code class="bash">(echo "import sys" ; echo "for r in range(10): print 'rob'" ) | python</code>
  • Using Alternate -c Options:

As suggested by SilentGhost and Crast (not shown in this response).

These solutions allow for the execution of multi-line Python statements within a single command-line command, while also importing necessary modules.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn