Skip to main content
 首页 » 编程设计

python之在没有脚本文件的情况下从命令行执行python程序

2025年05月04日23落叶无声

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

python程序有如下结构,虽然函数要复杂很多

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

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

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

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

请您参考如下方法:

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

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

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

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