在单行命令行中执行多行语句? [英] Executing multi-line statements in the one-line command-line?

查看:89
本文介绍了在单行命令行中执行多行语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Python与 -c 一起使用来执行单线循环,即:

I'm using Python with -c to execute a one-liner loop, i.e.:

$ python -c "for r in range(10): print 'rob'"

这很好。但是,如果在for循环之前导入模块,则会出现语法错误:

This works fine. However, if I import a module before the for loop, I get a syntax error:

$ python -c "import sys; for r in range(10): print 'rob'"
  File "<string>", line 1
    import sys; for r in range(10): print 'rob'
              ^
SyntaxError: invalid syntax

您知道如何解决此问题吗?

Any idea how this can be fixed?

对我来说,将其作为一个单行放置是很重要的,这样我才能将其包含在Makefile中。 / p>

It's important to me to have this as a one-liner so that I can include it in a Makefile.

推荐答案

您可以做到

echo -e "import sys\nfor r in range(10): print 'rob'" | python

或不带管道:

python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"


(echo "import sys" ; echo "for r in range(10): print 'rob'") | python

或@ SilentGhost的答案 / @ Crast的答案

这篇关于在单行命令行中执行多行语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆