Python:在“C:\***********\\MP7”中找不到“\\\*********”模块

2024-09-28 01:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手。我试图在windowcmd上编译代码。运行py文件时,错误是:C:\Python\Python38-32\Python.exe:在“C:\Users\tdd24\ECE 615 Vivado\MP7”中找不到“main”模块。我已经在jupyter笔记本中运行了部分代码,它没有这个错误。我找不到问题。有什么帮助吗

import serial
import struct


file1 = open(r'C:\Users\tdd24\ECE 615 Vivado\signal.txt', 'r')
Lines = file1.readlines()

ser = serial.Serial(
    port = 'COM4', # /dev/ttyUSB0 in Linux
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
    )
# Strips the newline character
for line in Lines:
    newpack = struct.pack('f', line)
    ser.write(newpack)
#############################    

file1.close()

ser.isOpen()
readbyte = 0
readstring = ""
print("Waiting for input")
while (readbyte != '\n'):
    readbyte = ser.read(1).decode("utf-8")
    readstring = readstring + readbyte
    
print(readstring)
ser.close()


我在cmd上使用的命令

Microsoft Windows [Version 10.0.19042.867]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\Users\tdd24>python --version
Python 3.8.5

C:\Users\tdd24>python "C:\Users\tdd24\ECE 615 Vivado\MP7"
C:\Python\Python38-32\python.exe: can't find '__main__' module in 'C:\\Users\\tdd24\\ECE 615 Vivado\\MP7'

C:\Users\tdd24>

Tags: 代码in错误serialexeusersfile1ser
1条回答
网友
1楼 · 发布于 2024-09-28 01:24:12

在windows上,需要在executed.py中包含以下内容

if __name__ == "__main__":

您可以将所有代码包装成一个函数并从main调用它,也可以将其嵌套在main中。前者可能是更好的选择,因为它开始了代码分段的过程

def Function1():
    file1 = open(r'C:\Users\tdd24\ECE 615 Vivado\signal.txt', 'r')
    Lines = file1.readlines()

    #This is your call below, I'm not sure it'll work with comments in the middle, but leaving unchanged to focus on the main point of your query.
    ser = serial.Serial(
        port = 'COM4', # /dev/ttyUSB0 in Linux
        baudrate=115200,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS
    )

    # Strips the newline character
    for line in Lines:
        newpack = struct.pack('f', line)
        ser.write(newpack)
    #############################    

    file1.close()

    ser.isOpen()
    readbyte = 0
    readstring = ""
    print("Waiting for input")
    while (readbyte != '\n'):
        readbyte = ser.read(1).decode("utf-8")
    readstring = readstring + readbyte

    print(readstring)
    ser.close()


if __name__ == "__main__":
    #Starting point for windows execution
    Function1()

相关问题 更多 >

    热门问题