【问题标题】:python SyntaxError when trying to import package BUT only when running remotely尝试导入包但仅在远程运行时出现python SyntaxError
【发布时间】:2013-07-31 19:57:25
【问题描述】:

我有以下脚本:

  1. test.py:

    import sys
    try:
        import random
        print random.random()
    except:
        print sys.exc_info()[0]
    
  2. 运行.sh:

    python "test.py" >> "test_file" ;
    

在我的 linux 服务器上运行以下命令时:

[saray@compute-0-15 ~]$  nohup ./run.sh  &

test_file 包含预期的随机数:

[saray@compute-0-15 ~]$  cat test_file
0.923051769631 

但是,当远程运行相同的命令时:

[saray@blob-cs ~]$ ssh "compute-0-15" 'nohup ./run.sh > /dev/null 2>&1 &'

python上传随机包失败!!

[saray@compute-0-15 ~]$ cat test_file
exceptions.SyntaxError

怎么了?

【问题讨论】:

    标签: python linux ssh


    【解决方案1】:

    您的远程计算机正在运行不同的 Python 版本,即 Python 3。

    在 Python 3 中,print 语句已替换为 print函数,并且您的代码引发了语法错误。

    解决方法是使用 Python 2 远程运行代码,或者使您的代码同时与 Python 2 和 3 兼容:

    from __future__ import print_function
    import sys
    
    import random
    print(random.random())
    

    【讨论】:

    • 但是仅仅调用python 仍然应该启动Python2。如果我们想要 Python3,它应该被寻址为python3。还是最近发生了变化?
    • @glglgl:取决于发行版。 Arch 和 Gentoo 在 Python 3 中使用 python。糟糕,糟糕的发行版!
    • @Martijn Pieters 许多发行版正在转换为 Python3 作为其默认版本。例如,预计 Ubuntu 13.10 将默认使用 Python3。如果您处于异构环境中,则显式指定所需的 Python 版本要安全得多>
    • @Jonathan:是的,这就是为什么在 Python 3 中使用 /usr/bin/python 的发行版很难处理; Debian、Ubuntu 和 RedHat / CentOS / Fedora 都使用python3
    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 2019-12-07
    • 2021-01-22
    • 2021-09-01
    • 1970-01-01
    • 2013-12-14
    • 2012-10-16
    • 2021-06-01
    相关资源
    最近更新 更多