将字符串作为参数传递给python脚本 [英] Passing a string as an argument to a python script
问题描述
我想将ZPL代码的字符串从一个python脚本传递到另一个python脚本.在第二个脚本中使用时,字符串格式错误.如何在不变形的情况下将字符串文字作为参数传递给另一个python脚本?
I want to pass a string of ZPL codes from one python script to another python script. The string becomes malformed when used in the second script. How can I pass a string literal as an argument to another python script without it being malformed?
原始字符串
^ XA ^ FO20,20 ^ BQ,2,3 ^ FDQA,001D4B02107A; 1001000; 49681207 ^ FS ^ FO50,50 ^ ADN,36,20 ^ FDMAC:001D4B02107A ^ FS ^ FO50,150 ^ ADN,36,20 ^ FDSN:1001000 ^ FS ^ FO50,250 ^ ADN,36,20 ^ FDCode:49681207 ^ FS ^ XZ
格式错误的字符串
XAFO20,20BQ,2,3FDQA,001D4B02107A; 1001000; 49681207FSFO50,50ADN,36,20FDMAC:
我在其中调用第二个脚本的代码
def printLabel():
label = "^XA"+"^FO20,20^BQ,2,3^FDQA,"+"001D4B02107A;1001000;49681207"+"^FS"+"^FO50,50"+"^ADN,36,20"+"^FD"+"MAC: "+"001D4B02107A"+"^FS"+"^FO50,150"+"^ADN,36,20"+"^FD"+"SN: "+"1001000"+"^FS"+"^FO50,250"+"^ADN,36,20"+"^FD" + "Code: "+"49681207"+"^FS"+"^XZ"
command = "zt320print.py "+label
print command
sys.stdout.flush()
exitCode = os.system(str(command))
接收自变量的代码
if __name__ == "__main__":
zplString = str(sys.argv[1])
print zplString
printZPL(zplString)
推荐答案
如果您的代码需要照原样编写(包括将ZPL代码串起来,并通过shell中介程序调用单独脚本的相当奇怪的方式),并避免使用 subprocess
),您可以通过一些小的调整来解决您的问题:
If your code needs to be written just as it is (including the rather odd way of stringing together the ZPL code, and calling a separate script via a shell intermediary, and the avoidance of subprocess
, for that matter), you can resolve your issue with a few small adjustments:
首先,将代码字符串用双引号引起来.
First, wrap your code string in double-quotes.
label= '"^XA'+"^FO20,20^BQ,2,3^FDQA,"+"001D4B02107A;1001000;49681207"+"^FS"+"^FO50,50"+"^ADN,36,20"+"^FD"+"MAC: "+"001D4B02107A"+"^FS"+"^FO50,150"+"^ADN,36,20"+"^FD"+"SN: "+"1001000"+"^FS"+"^FO50,250"+"^ADN,36,20"+"^FD" + "Code: "+"49681207"+"^FS"+'^XZ"'
第二,确保您实际上是在从外壳程序中调用 python
:
Second, make sure you're actually calling python
from the shell:
command = "python script2.py "+label
最后,如果您担心无法从命令行正确读取特殊字符,请使用 codecs.decode
中的 unicode_escape
来确保正确传输.
有关 unicode_escape
的更多信息,请参见此答案.
Finally, if you're concerned about special characters not being read in correctly from the command line, use unicode_escape
from codecs.decode
to ensure correct transmission.
See this answer for more on unicode_escape
.
# contents of second script
if __name__ == "__main__":
from codecs import decode
import sys
zplString = decode(sys.argv[1], 'unicode_escape')
print(zplString)
现在,您第一个脚本的调用将正确传输代码:
Now the call from your first script will transmit the code correctly:
import sys
import os
sys.stdout.flush()
exitCode = os.system(str(command))
输出:
^XA^FO20,20^BQ,2,3^FDQA,001D4B02107A;1001000;49681207^FS^FO50,50^ADN,36,20^FDMAC: 001D4B02107A^FS^FO50,150^ADN,36,20^FDSN: 1001000^FS^FO50,250^ADN,36,20^FDCode: 49681207^FS^XZ
这篇关于将字符串作为参数传递给python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!