【问题标题】:How to use python -c "code here" with newlines?如何使用带有换行符的 python -c “code here”?
【发布时间】:2021-03-02 20:47:31
【问题描述】:

命令

python -c "print('hello')"

在 Linux (bash) 和 Windows (cmd.exe) 中成功运行引号内的代码。

但是如何使用换行符和python -c 传递代码?

示例:两者

python -c "for i in range(10): if i % 2 == 0: print('hello')"
python -c "for i in range(10):\n    if i % 2 == 0:\n        print('hello')"

失败。


示例用例:我需要发送一个 SSH 命令(使用 paramiko)在远程服务器上执行一个简短的 Python 代码,所以我需要传递一个命令,例如
ssh.exec_command('python -c "..."')

【问题讨论】:

  • 你可以在 bash 中使用 $'foo bar' 字符串

标签: python bash cmd command-line


【解决方案1】:

一种方法是使用exec(),使字符串可执行。它看起来很糟糕,但它确实有效。

python -c "exec(\"for i in range(10):\n if i % 2 == 0:\n  print('hello')\")"

【讨论】:

    【解决方案2】:

    您可以使用 bash 的 $'foo' 字符串语法来获取换行符:

    python -c $'for i in range(10):\n if i % 2 == 0:\n  print("hello")'
    

    (我在这里使用单个空格缩进)

    对于windows,你真的应该使用powershell,它有`n作为换行符:

    python -c "for i in range(10):`n if i % 2 == 0:`n  print('hello')"
    

    在 cmd.exe 中,您似乎可以使用 ^ 转义换行符,但是我目前无法对此进行测试,因此您应该使用 refer to this question's answers

    【讨论】:

      【解决方案3】:

      虽然不使用-c,但值得一提的是,如果使用Bash,您可以将回显代码直接通过管道传送到python

      echo -e 'for i in range(10):\n if i % 2 == 0:\n  print("hello")' | python
      

      遵循 Aplet123 的引导并使用单个空格缩进。

      【讨论】:

        【解决方案4】:

        您可以使用bash “heredoc”(也可以使用ksh 和POSIX shell):

        python <<EOF
        import numpy as np
        print(dir(np))
        EOF
        

        【讨论】:

        • @Basj 也许考虑更新您的问题,以便更好地代表您实际尝试做的事情。
        猜你喜欢
        • 2017-05-08
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 2016-12-22
        • 2018-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多