Maison >développement back-end >Tutoriel Python >Comment exécuter des commandes multilignes dans une seule ligne de commande ?
How to Execute Multi-Line Statements in a One-Line Command Line
When executing a single-line loop with Python's -c option, importing a module before the loop results in a syntax error. This is because the Python interpreter treats the code block as a single statement.
To resolve this issue, several methods can be employed:
Using Pipes
To overcome the syntax error, use the echo command to redirect the code block to Python as a series of input lines:
echo -e "import sys\nfor r in range(10): print 'rob'" | python
Using exec()
Another approach is to use the exec() function to execute the code block as a Python script:
python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"
Expanding to Multiple Lines
If using pipes or exec() is not feasible, the code block can be expanded to multiple lines separated by semicolons:
(echo "import sys" ; echo "for r in range(10): print 'rob'" ; echo "exec(\"import sys\nfor r in range(10): print 'rob'")") | python
By utilizing these techniques, you can execute multi-line statements in a single command line while maintaining the desired structure for your Makefile.
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!