从命令行执行python程序,无需脚本文件

pat*_*fox 6 python bash

我想在远程服务器上执行 python 程序,而不创建脚本。远程服务器不允许我在文件系统上的任何位置创建任何文件。

python程序具有以下结构,尽管功能要复杂得多

def test2():
  print("test2")

def test_func():
  test2()
  print("test_func")

test_func()
Run Code Online (Sandbox Code Playgroud)

有没有办法直接从命令行执行这个程序?
我尝试过这两种方法

  1. 使用python -c选项传递代码。
  2. 启动python交互模式,然后复制粘贴代码来运行。

我在这两种情况下都会出错。但是,任何没有用户定义函数的代码都可以使用第二种方法执行。是否可以在不创建本地脚本的情况下使上面的代码正常工作?

Dru*_*lan 9

我找到了一个解决方案,也许会有帮助,你可以使用EOF

$ python << EOF
> def test2():
>   print("test2")
> 
> def test_func():
>   test2()
>   print("test_func")
> 
> test_func()
> EOF

# output
test2
test_func
Run Code Online (Sandbox Code Playgroud)

您还可以python -c使用"""

$ python -c """
def test2():
  print("test2")

def test_func():
  test2()
  print("test_func")

test_func()
"""
Run Code Online (Sandbox Code Playgroud)


Eug*_*ako 5

您仍然可以像第一个一样使用函数:

$ printf "def f():\n    print 'hello'\n\nf()" | python
hello
Run Code Online (Sandbox Code Playgroud)