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
Answer from andrew_reece on Stack Overflow
Top answer
1 of 3
2

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
2 of 3
0

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'

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

label = '"' + label + '"'
Discussions

ssh - How to pass string from bash to python function - Unix & Linux Stack Exchange
Can anyone explain why the behavior ... bash script to python function ... This question is really "how do I pass strings to a python program" (and it's not done the way you do it), and it's honestly a programming question. To make this really short: you want to use command line arguments, or passing ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
python - Pass in string as argument without it being treated as raw - Stack Overflow
I want to pass in a string to my python script which contains escape sequences such as: \x00 or \t, and spaces. However when I pass in my string as: some string\x00 more \tstring python treats my More on stackoverflow.com
🌐 stackoverflow.com
Bash pass string argument to python script - Stack Overflow
Works perfectly with python argparse. 2016-06-19T20:29:30.58Z+00:00 ... where the first argument to get is the variable name and the second is the default value used should the var not be in the environment. ... That's not right. That would turn my_param_str into a single argument of the form --my_param Some -- string... More on stackoverflow.com
🌐 stackoverflow.com
Pass an argument to a Python script
Use sys.argv https://docs.python.org/3/library/sys.html#sys.argv More on reddit.com
🌐 r/learnpython
7
1
March 6, 2021
🌐
IncludeHelp
includehelp.com › python › passing-string-value-to-the-function.aspx
Python | Passing string value to the function
# Python program to pass a string to the function # function definition: it will accept # a string parameter and print it def printMsg(str): # printing the parameter print(str) # Main code # function calls printMsg("Hello world!") printMsg("Hi! I am good.") ... Hello world! Hi! I am good. Write function that will accept a string and return total number of vowels
🌐
Python Course
python-course.eu › python-tutorial › passing-arguments.php
25. Passing Arguments | Python Tutorial | python-course.eu
Correctly speaking, Python uses a mechanism, which is known as "Call-by-Object", sometimes also called "Call by Object Reference" or "Call by Sharing". If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value.
Find elsewhere
Top answer
1 of 2
6

argv will be a list of all the arguments that the shell parses.

So if I make

#script.py
from sys import argv
print argv

$python script.py hello, how are you
['script.py','hello','how','are','you]

the name of the script is always the first element in the list. If we don't use quotes, each word will also become an element of the list.

print argv[1]
print argv[2]
$python script.py hello how are you
hello
how

But if we use quotes,

$python script.py "hello, how are you"
 ['script.py','hello, how are you']

The all words are now one item in the list. So do something like this

print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", argv[1]

Or if you don't want to use quotes for some reason:

print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", " ".join(argv[1:]) #slicing the remaining part of our list and joining it as a string.

$python script.py hello, how are you
$The script is called: script.py
$Your first variable is: hello, how are you
2 of 2
1

Multi word command line arguments, that is single value arguments that contain multiple ASCII sequences separated by the space character %20 have to be enclosed with quotes on the command line.

$ python test.py "f i r s t a r g u m e n t"
The script is called:test.py
Your first variable is:f i r s t a r g u m e n t

This is actually not related to Python at all, but to the way your shell parses the command line arguments.

Top answer
1 of 2
5

First (and probably most preferable) solution is to put the second and third argument in quotes as Susmit Agrawal suggested. Then the shell itself will split the command line into arguments appropriately.

python mytest.py [email protected]  "value of file 1"  "value of file 2"

In case you really need to pass arguments without quotes though, you will have to accept that the shell will be splitting your second and third argument at spaces, so you will need to reconstruct them from sys.argv yourself.

Lastly, you may want to explore argparse library to help you with parsing the command line arguments. In this case you may want to use optional arguments with nargs set to '+' or some certain number based on your command line API. For example, if you define and parse your arguments the following way,

parser = argparse.ArgumentParser()
parser.add_argument('--value-1', nargs=4)
parser.add_argument('--value-2', nargs=4)
parser.add_argument('email', nargs='+')
args = parser.parse_args()

print(args)

then you can call your Python program as

python mytest.py [email protected]  --value-1 value of file 1  --value-2 value of file 2

And get the following result,

Namespace(email=['[email protected]'], value_1=['value', 'of', 'file', '1'], value_2=['value', 'of', 'file', '2'])

which you can then conveniently access as

print(args.value_1)
print(args.value_2)
print(args.email)
2 of 2
0

you can use argparse to pass your argument:

import argparse 

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-stv1', type=str)
    parser.add_argument('-stv2', type=str)
    parser.add_argument('-email', nargs='+')
    args = parser.parse_args()
    print(args)

nargs='+' indicate that at least you should pass one argument as email or more.

Executing the script give the following :

python3 script.py -email [email protected] [email protected] -stv1 "value of file 1" -stv2 "value of file 2" 

Namespace(email=['[email protected]', '[email protected]'], stv1='value of file 1', stv2='value of file 2')

🌐
LogicMonitor
community.logicmonitor.com › tech forums › product discussions
To pass a string to python script using Linux/Unix Script parameters from datasource | LogicMonitor - 11030
We are able to pass the customer name if it is a single word i.e SPU but if we try to pass the customer name with space inbetween i.e "SPU UPS" its not working. we have tried with Underscore inbetween i.e "SPU_UPS" its working, but we think underscore also passing as a value and not indicating space between the words while passing to the python script.
🌐
GeeksforGeeks
geeksforgeeks.org › command-line-arguments-in-python
Command Line Arguments in Python - GeeksforGeeks
# Python program to demonstrate # command line arguments import sys # total arguments n = len(sys.argv) print("Total arguments passed:", n) # Arguments passed print("\nName of Python script:", sys.argv[0]) print("\nArguments passed:", end = " ") for i in range(1, n): print(sys.argv[i], end = " ") # Addition of numbers Sum = 0 # Using argparse module for i in range(1, n): Sum += int(sys.argv[i]) print("\n\nResult:", Sum) ... Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module extends the separation of the input string by parameter validation.
Published   March 17, 2025
🌐
Tutorialspoint
tutorialspoint.com › python › python_command_line_arguments.htm
Python - Command-Line Arguments
By default, all arguments are treated as strings. To explicitly mention type of argument, use type parameter in the add_argument() method. All Python data types are valid values of type.
🌐
UiPath Community
forum.uipath.com › help › activities
Argument passing in python script - Activities - UiPath Community Forum
Hey, I’m working with the invoke python method in UIPaths I want to pass 3 arg to python fuction 2 string and one python obj how can I do that??
Published   September 22, 2023
Top answer
1 of 3
24

You can use the sys module like this to pass command line arguments to your Python script.

import sys

name_of_script = sys.argv[0]
position = sys.argv[1]
sample = sys.argv[2]

and then your command line would be:

./myscript.py 10 100
2 of 3
16

Use argparse module:

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

It's pretty powerful: you can specify help messages, make validations, provide defaults..whatever you can imagine about working with command-line arguments.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--position", type=int)
parser.add_argument("-s", "--sample", type=int)

args = parser.parse_args()
col = args.position
sample = args.sample

print col
print sample

Here's what on the command-line:

$ python test.py --help
usage: test.py [-h] [-p POSITION] [-s SAMPLE]

optional arguments:
  -h, --help            show this help message and exit
  -p POSITION, --position POSITION
  -s SAMPLE, --sample SAMPLE

$ python test.py -p 10 -s 100
10
100
$ python test.py --position 10 --sample 100
10
100

Speaking about the code you've provided:

  • unused import random statement
  • move from random import shuffle to the top of the script
  • no need to call f.close() (especially with ;) - with handles closing the file automagically

Here's how the code would look like after the fixes:

#!/usr/bin/python
import argparse
import csv
from random import shuffle


parser = argparse.ArgumentParser()
parser.add_argument("-p", "--position", type=int)
parser.add_argument("-s", "--sample", type=int)

args = parser.parse_args()

with open('<filename>', 'r') as f:
    reader = csv.reader(f)
    data = [row[args.position] for row in reader]
    shuffle(data)
    print '\n'.join(data[:args.sample])
🌐
Python
docs.python.org › 3.3 › library › argparse.html
16.4. argparse — Parser for command-line options, arguments and sub-commands — Python 3.3.7 documentation
All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are: prog - The name of the program (default: sys.argv[0]) usage - The string describing the program usage (default: generated from arguments added to parser)
🌐
AskPython
askpython.com › home › python command line arguments – 3 ways to read/parse
Python Command Line Arguments - 3 Ways to Read/Parse - AskPython
December 16, 2019 - If you want to pass command-line arguments to a python program, go to “Run > Edit Configurations” and set the Parameters value and save it. ... There are three popular modules to read and parse command-line arguments in the Python script.
🌐
OpenSourceOptions
opensourceoptions.com › how-to-pass-arguments-to-a-python-script-from-the-command-line
How to Pass Arguments to a Python Script from the Command Line – OpenSourceOptions
In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys (sys.argv) will store all the information in the command line entry and can be accessed inside the Python script.