如何在代码中嵌入文本文件?

时间:2017-12-24 19:02:28

标签: python

我有一个Python代码来运行我的CNC机器,代码如下:

import serial
import time

# Open grbl serial port
s = serial.Serial('COM3',9600)

# Open g-code file
f = open('grbl.gcode.txt','r');

# Wake up grbl
s.write("\r\n\r\n")
time.sleep(2)   # Wait for grbl to initialize
s.flushInput()  # Flush startup text in serial input

# Stream g-code to grbl
for line in f:
    l = line.strip() # Strip all EOL characters for consistency
    print 'Sending: ' + l,
    s.write(l + '\n') # Send g-code block to grbl
    grbl_out = s.readline() # Wait for grbl response with carriage return
    print ' : ' + grbl_out.strip()

# Wait here until grbl is finished to close serial port and file.
raw_input("  Press <Enter> to exit and disable grbl.")

# Close file and serial port
f.close()
s.close()

此代码打开g代码文件(它是一个文本文件)并执行这些行。我的问题是我可以摆脱g代码的文本文件并将其直接放在上面的代码中吗?

1 个答案:

答案 0 :(得分:2)

而不是

f = open('grbl.gcode.txt','r')
for line in f:
    # do your stuff

你可以

mycmds = """
put your
commands
into
here
"""

for line in mycmds:
    # do your stuff