Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在没有脚本文件的情况下从命令行执行python程序_Python_Bash - Fatal编程技术网

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

在没有脚本文件的情况下从命令行执行python程序,python,bash,Python,Bash,我想在远程服务器上执行python程序,而不创建脚本。远程服务器不允许我在文件系统的任何位置创建任何文件 python程序具有以下结构,尽管函数要复杂得多 def test2(): print("test2") def test_func(): test2() print("test_func") test_func() 有没有办法直接从命令行执行此程序? 我试过这两种方法 使用python-c选项传递代码 启动python交互模式,并复制粘贴要运行的代码 这两种情况下我都会出

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

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

def test2():
  print("test2")

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

test_func()
有没有办法直接从命令行执行此程序?
我试过这两种方法

  • 使用python-c选项传递代码
  • 启动python交互模式,并复制粘贴要运行的代码

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

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

    $ printf "def f():\n    print 'hello'\n\nf()" | python
    hello
    

    如果您可以将python源代码存储在HTTP服务器上,并且在远程主机上安装了
    wget
    (或类似版本)

    $wget-O-http://my.server.de/some/path/my_program.py |蟒蛇
    
    可能是实现目标的一种廉价方式

    另一种可能性是,不涉及HTTP服务器,但您需要在远程主机上使用
    scp
    ssh

    $scp my_host:a_python_file.py/dev/stdout|python
    $ssh my_host'cat a_python_file.py'| python
    
    我找到了一个解决方案,也许会有帮助,你可以使用
    EOF

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

    在方法2中会出现什么错误?@kaustubh我更新了我的答案,你甚至可以使用带有三个引号的
    python-c
    ,这也会起作用。没有理由使用三个引号,这是由shell计算的。单引号也能很好地工作。@GBOFI您是对的,使用单引号或双引号工作,但使用三个引号时,您不关心使用哪种类型的引号来定义变量
    a='a'
    a=“a”
    。Python没有看到三个引号,前两个引号(在第1行)由shell解释为空字符串,最后的2(在最后一行中)也被解释为空字符串。请检查您的陈述,然后自己更正。如果您想从终端输入脚本,这种方法是最好的,因为它避免了引用任何问题。。。
    $ python -c """
    def test2():
      print("test2")
    
    def test_func():
      test2()
      print("test_func")
    
    test_func()
    """