本文介绍了Shebang 不适用于 python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序:

#!/usr/local/bin/python3

print("Hello")

通过终端我做 test.py 并且我得到:

Via terminal I do test.py and I get:

Traceback (most recent call last):
  File "/usr/lib/python3.3/site.py", line 629, in <module>
    main()
  File "/usr/lib/python3.3/site.py", line 614, in main
    known_paths = addusersitepackages(known_paths)
  File "/usr/lib/python3.3/site.py", line 284, in addusersitepackages
    user_site = getusersitepackages()
  File "/usr/lib/python3.3/site.py", line 260, in getusersitepackages
    user_base = getuserbase() # this will also set USER_BASE
  File "/usr/lib/python3.3/site.py", line 250, in getuserbase
    USER_BASE = get_config_var('userbase')
  File "/usr/lib/python3.3/sysconfig.py", line 610, in get_config_var
    return get_config_vars().get(name)
  File "/usr/lib/python3.3/sysconfig.py", line 560, in get_config_vars
    _init_posix(_CONFIG_VARS)
  File "/usr/lib/python3.3/sysconfig.py", line 432, in _init_posix
    from _sysconfigdata import build_time_vars
  File "/usr/lib/python3.3/_sysconfigdata.py", line 6, in <module>
    from _sysconfigdata_m import *
ImportError: No module named '_sysconfigdata_m'

相反,如果我输入 python3 test.py 它可以工作,我得到:

Instead if I type python3 test.py it works, I get:

你好

附言which python3 ----> /usr/local/bin/python3

推荐答案

一般来说,注意一些陷阱:

Generally, take care of some pitfalls:

  1. 在脚本上设置可执行标志:chmod u+x test.py

尝试使用前面的点执行./",所以调用 ./test.py 否则它可能会从内部执行一些其他脚本你的 PATH

try to execute with a preceding dot "./", so call ./test.py otherwise it might execute some other script from within your PATH

还要确保你没有windows行尾,这似乎也阻止了shebang评估.周围有一些建议,例如在这个答案中,关于如何转换格式.

also make sure you don't have windows line endings, this seems to prevent the shebang evaluation, too. There are some suggestions around, e.g. in this answer, on how to convert the format.

如果 python3 test.py 有效,那么 windows 行尾可能是你的问题.

If python3 test.py works, then the windows line endings are probably your problem.

#!/usr/bin/env python3 是定义shebang的最佳方式(即使用它作为脚本的第一行),因为python 二进制文件可能安装在其他地方.env 将检查 PATH 环境以找到二进制文件

#!/usr/bin/env python3 is the best way to define the shebang (i.e. use this as first line of your script), since the python binary may be installed somewhere else. env will inspect the PATH environment to find the binary

正如@ShaileshKumarMPatel 在此处的评论中指出的那样,请确保没有错误的行开头(颜色字符等)

As @ShaileshKumarMPatel has pointed out in the comments here, make sure, there's no wrong line beginnings (color characters etc)

OP 的错误类型对我来说就像是 windows 行结尾.我也有它们,但输出不同

The OP's kind of error looks like windows line endings to me. I've had them, too, with different output though

这篇关于Shebang 不适用于 python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:52
查看更多