在python3中导入模块

时间:2015-05-17 02:24:45

标签: python

我把hello.py放在Users / apple / Documents中,当我尝试在IDLE中导入这个模块时,输出中有一个SyntaxError。

hello.py(文件中的所有内容):

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.

WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
Visit http://www.python.org/download/mac/tcltk/ for current information.

print('helloworld')

命令我尝试在Python解释器中运行

import sys
sys.path
['', '/Users/apple/Documents', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages']

import hello

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import hello
File "/Users/apple/Documents/hello.py", line 1
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
^
SyntaxError: invalid syntax

我跟着这本书去了终端:

appletekiMacBook-Pro:~ apple$ python hello.py

python: can't open file 'hello.py': [Errno 2] No such file or directory

appletekiMacBook-Pro:~ apple$ chmod a+x hello.py
chmod: hello.py: No such file or directory


appletekiMacBook-Pro:~ apple$ ./hello.py
-bash: ./hello.py: No such file or directory

2 个答案:

答案 0 :(得分:1)

您的hello.py文件包含无效的Python语法。错误消息

File "/Users/apple/Documents/hello.py", line 1
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
^
SyntaxError: invalid syntax

指示文件的第一行包含不是有效Python语法的文本Python 3.4.3 (v3...etc)。编辑你的hello.py文件,使其如下所示:(将#添加到前几行的前面)

# Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information.

# WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ for current information.

print('helloworld')

你得到的原因&#39;没有这样的文件或目录&#39;当你试图从终端运行它是因为你实际上并没有在正确的位置寻找它。

提示中的

appletekiMacBook-Pro:~ apple$表示您当前的工作目录是您的主目录(/ Users / apple /),但是从错误消息中,hello.py位于Documents /子目录中。如果将命令更改为

appletekiMacBook-Pro:~ apple$ python Documents/hello.py

然后一旦前几行被注释掉它就会运行。

答案 1 :(得分:1)

第二个问题很简单,你看错了目录。

你说:

  

我把hello.py放在Users / apple / Documents

然后你:

appletekiMacBook-Pro:~ apple$ python hello.py

~是您的主目录,hello.py位于/Users/apple/Documents。您应该执行cd Documents然后运行上面的命令。