Skip to content Skip to sidebar Skip to footer

Passing A String As An Argument To A Python Script

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

Solution 1:

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"'

Second, make sure you're actually calling python from the shell:

command = "python script2.py "+label

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))

Output:

^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

Solution 2:

Some demo code:

import sys

if __name__ == "__main__":
    for i, arg in enumerate(sys.argv):
        print("{}: '{}'".format(i, arg))

when called like

python test.py ^this^is^a^test

it gives

0: 'test.py'
1: 'thisisatest'

when called like

python test.py "^this^is^a^test"

it gives

0: 'test.py'
1: '^this^is^a^test'

Answer : enclose your parameter string in double-quotes, ie

label = '"' + label + '"'

Solution 3:

You can put your string inside a double-quotes, or just import the other python script:

a.py

import sys, os

text = "a b c d"

# or '{} {} "{}"'.format("python", "b.py", text)
command = "python b.py \"" + text + "\"" 
os.system(str(command))

b.py

import sys

if __name__ == "__main__":

    first_argument = str(sys.argv[1])
    print(first_argument)

Output

a b c d


Post a Comment for "Passing A String As An Argument To A Python Script"