Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.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系列可以在shell中工作,但不能在脚本中工作?_Python_Shell_Serial Port_Arduino - Fatal编程技术网

Python系列可以在shell中工作,但不能在脚本中工作?

Python系列可以在shell中工作,但不能在脚本中工作?,python,shell,serial-port,arduino,Python,Shell,Serial Port,Arduino,我正在尝试一个关于Arduino的例子: 该示例(在Ubuntu上运行)在shell中运行良好: import serial ser = serial.Serial('/dev/ttyACM0', 9600) while True: print(ser.readline()) 但是,尝试作为脚本执行时: 桌面/python\u arduino//serial.py 它执行以下操作: #!/usr/bin/env python import serial ser = serial.

我正在尝试一个关于Arduino的例子:

该示例(在Ubuntu上运行)在shell中运行良好:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

while True:
    print(ser.readline())
但是,尝试作为脚本执行时:

桌面/python\u arduino//serial.py

它执行以下操作:

#!/usr/bin/env python
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

while True:
    print(ser.readline())
我明白了:

Traceback (most recent call last):
  File "Desktop/python_arduino/./serial.py", line 2, in <module>
    import serial
  File "/home/leo/Desktop/python_arduino/serial.py", line 4, in <module>
    ser = serial.Serial('/dev/ttyACM0', 9600)
AttributeError: 'module' object has no attribute 'Serial'
回溯(最近一次呼叫最后一次):
文件“Desktop/python\u arduino//serial.py”,第2行,在
导入序列号
文件“/home/leo/Desktop/python_ardino/serial.py”,第4行,在
ser=serial.serial('/dev/ttyACM0',9600)
AttributeError:“模块”对象没有属性“序列”

是什么导致了这种不一致?无论shell或脚本是什么,都应该很容易导入串行,对吗?

shell和脚本之间的区别可能是不同的路径设置。比较路径,看看脚本和shell是否有什么不同

import ser
print ser.__file__

import sys
print sys.executable
我找到了

这个问题其实很微妙但很简单

脚本文件名与导入文件名相同

所以文件名是serial.py。该模块称为串行,因此产生了冲突


我更改了脚本的文件名,它成功了

是什么导致了您观察到的行为?请参阅下面我的答案。脚本文件名与导入文件名相同。所以文件名是serial.py。该模块称为串行模块。我更改了脚本的文件名,它成功了。我还必须删除
.pyc
文件。