Try separating the values with commas:

subprocess.call(['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, '-u', _userid, _username])

See http://docs.python.org/library/subprocess.html#subprocess.call - It takes an array where the first argument is the program and all other arguments are passed as arguments to the program.

Also don't forget to check the return value of the function for a zero return code which means "success" unless it doesn't matter for your script if the user was added successfully or not.

Answer from ThiefMaster on Stack Overflow
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
5 days ago - However, this can only be done if not passing arguments to the program. ... It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success!
Discussions

How can I pass arguments to subprocess.call or subprocess.run for execution in PS?
not sure if the powershell actual command is the right one.<3 the python code for the call looks good. , shell=True) ? More on reddit.com
🌐 r/learnpython
22
10
July 11, 2021
Python subprocess arguments - Stack Overflow
Each argument needs to be separated when subprocess.call is used with shell=False (the default). You can also specify shell=True and give the whole command as a single string, but this is not recommended due to potential security vulnerabilities. You should not need to use string formatting where you have "%s" % url. If url is a string, pass ... More on stackoverflow.com
🌐 stackoverflow.com
How to pass arguments in python subprocess? - Stack Overflow
As explained here: https://docs.python.org/3/library/subprocess.html, you can add in the array every argument you would normally pass in a command-line. For example, if you wanted to run ls -l --color=auto, you could write: More on stackoverflow.com
🌐 stackoverflow.com
python - How to pass arguments to subprocess - Stack Overflow
I want run a process called client.sh in gnome-terminal via python script and want to pass the arguments as input to execute it. Below is my code import os import subprocess import time from subp... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Gilad Naor
blog.giladnaor.com › 2009 › 09 › python-subprocess-and-multiple.html
Python, Subprocess and Multiple Arguments - Gilad Naor
September 26, 2009 - It’s the third option that keeps ... output · If you want to pass arguments that are passed with quotes in the shell, then just pass them as a single list item, without the quotes....
🌐
Reddit
reddit.com › r/learnpython › how can i pass arguments to subprocess.call or subprocess.run for execution in ps?
r/learnpython on Reddit: How can I pass arguments to subprocess.call or subprocess.run for execution in PS?
July 11, 2021 -

Hello,

I'm trying to launch a powershell script via subprocess.call or subprocess.run, but I'm having trouble with how to specify the arguments for a function in powershell.

For example, in a powershell script I have a function Foo which accepts a string. With subprocess I would like to launch this script and pass an argument to Foo.

How can I do that?

In order to simply call the script I managed to do it in the following way:

if is_admin():
    # If launched as admin - good
    cmd = ["PowerShell", "-ExecutionPolicy", "Unrestricted", "-File", absolute_path]
    ec = subprocess.call(cmd)
    print("Powershell returned: {0:d}".format(ec))
else:
    # If not admin, relaunch as admin
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
🌐
DataCamp
datacamp.com › tutorial › python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - The subprocess.run() method takes several arguments, some of which are: args: The command to run and its arguments, passed as a list of strings.
🌐
Python 101
python101.pythonlibrary.org › chapter19_subprocess.html
Chapter 19 - The subprocess Module — Python 101 1.0 documentation
Or you could just put all this code into a saved Python file and run that. Note that using the wait method can cause the child process to deadlock when using the stdout/stderr=PIPE commands when the process generates enough output to block the pipe. You can use the communicate method to alleviate this situation. We’ll be looking at that method in the next section. Now let’s try running Popen using multiple arguments: >>> subprocess.Popen(["ls", "-l"]) <subprocess.Popen object at 0xb7451001>
Find elsewhere
🌐
Python
docs.python.org › 3.4 › library › subprocess.html
17.5. subprocess — Subprocess management — Python 3.4.10 documentation
June 16, 2019 - The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if universal_newlines=True.
🌐
Stack Overflow
stackoverflow.com › questions › 49706015 › how-to-pass-arguments-to-subprocess › 49707454
python - How to pass arguments to subprocess - Stack Overflow
Below is my code · import os import subprocess import time from subprocess import Popen,PIPE import pexpect process = subprocess.Popen('sudo gnome-terminal -x ./client.sh', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) process.communicate(input ...
🌐
Reddit
reddit.com › r/learnpython › how do i pass arguments to another function with subprocess.popen?
r/learnpython on Reddit: How do I pass arguments to another function with subprocess.Popen?
February 27, 2022 -

Hi! I use Subprocess.Popen to specificly call a function from another python module/script.

This works:

subprocess.Popen(["python", "-c",
"import " + "main" + ";" + "main" + "." + "func" + "()"])

However, say I have some global variables from the python script I call this function, how would I pass these into subprocess.Popen? Like this:

arg1 = 2, arg2 = 4

subprocess.Popen(["python", "-c",
"import " + "main" + ";" + "main" + "." + "func" + "(arg1, arg2)"])

Above example does not work. How can I make it work?

🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Pass variable to subprocess.Popen - Python
gkreidl wrote:You pass the string "tlog" and not the variable. Remove the double quotes. Are you sure ? Have you tried your solution for yourself ? It doesn't seem to work for me ... >>> import subprocess >>> n = 10 >>> subprocess.Popen(["./args","hello",n]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception TypeError: execv() arg 2 must contain only strings You need
🌐
GitHub
hplgit.github.io › primer.html › doc › pub › tech › ._tech-solarized012.html
Technical topics
import subprocess cmd = 'python myprog.py 21 --mass 4' failure = subprocess.call(cmd, shell=True) # or failure = subprocess.call( ['python', 'myprog.py', '21', '--mass', '4']) The output of an operating system command can be stored in a string object: try: output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: print 'Execution of "%s" failed!\n' % cmd sys.exit(1) # Process output for line in output.splitlines(): ... The stderr argument ensures that the output string contains everything that the command cmd wrote to both standard output and standard error.
🌐
Linux Mint Forums
forums.linuxmint.com › board index › interests › programming & development
[SOLVED] Python: how to pass argument containing blank space with subprocess? - Linux Mint Forums
September 19, 2024 - subprocess.run(["pandoc", input_file, "-V", "geometry:a4paper,margin=3cm", "-V", "mainfont=\"DejaVu Sans\"", "--pdf-engine=xelatex", "-o", output_file]) Using this syntax pandoc throws an error complaining it can't find "DejaVu" font while the actual font it should be looking for is "DejaVu Sans".
🌐
Dataquest
dataquest.io › blog › python-subprocess
Python Subprocess: The Simple Beginner's Tutorial (2023)
February 19, 2025 - In fact, this is the same as passing /usr/local/bin/python -c print('This is a subprocess') to the command line. Most of the code in this article will be in this format because it's easier to show the features of the run function.
🌐
Stack Overflow
stackoverflow.com › questions › 73383521 › how-to-pass-arguments-to-subprocess-python-instance
How to pass arguments to subprocess python instance - Stack Overflow
from time import sleep from multiprocessing import Process import subprocess def task1(): print('This is task1') subprocess.Popen(['python','server_client_pair1.py']) sleep(1) def task2(): # block for a moment sleep(1) # display a message print('This is task2') p1 = subprocess.Popen(['python','server_client_pair2.py']) sleep(1) if __name__ == '__main__': # create a process process1 = Process(target=task1) sleep(.5) process2 = Process(target=task2) sleep(.5) # run the process process1.start() sleep(.5) process2.start() sleep(.5) # wait for the process to finish print('Waiting for the process...') process1.join() process2.join() I need to pass argument which changes variable PORT which is port number and I'd like to change it with PORT+1 every loop in the file ('server_client_pair.py')
🌐
Python Forum
python-forum.io › thread-11422.html
How to pass arguments to popen?
I'm trying to pass an argument to the popen function below. I've tried various permutations of syntax, and still can't get it working. What I ultimately want to do is pass an argument to the script, i.e., sys.argv. Can someone show me the syntax f...
Top answer
1 of 4
21

The subprocess library is interpreting all of your arguments, including demo_oled_v01.py as a single argument to python. That's why python is complaining that it cannot locate a file with that name. Try running it as:

p = subprocess.Popen(['python', 'demo_oled_v01.py', '--display',
'ssd1351', '--width', '128', '--height', '128', '--interface', 'spi',
'--gpio-data-command', '20'])

See more information on Popen here.

2 of 4
7

This started as a comment thread, but got too long and complex.

Calling Python as a subprocess of Python is an antipattern. You can often fruitfully avoid this by refactoring your Python code so that your program can call the other program as a simple library (or module, or package, or what have you -- there is a bit of terminology here which you'll want to understand more properly ... eventually).

Having said that, there are scenarios where the subprocess needs to be a subprocess (perhaps it is designed to do its own signal handling, for example) so don't apply this blindly.

If you have a script like demo.py which contains something like

def really_demo(something, other, message='No message'):
    # .... some functionality here ...

def main():
    import argparse
    parser = argparse.ArgumentParser(description='Basic boilerplate, ignore the details.')
    parser.add_argument('--something', dest='something')  # store argument in args.something
    parser.add_argument('--other', dest='other')  # ends up in args.other
    # ... etc etc etc more options
    args = parser.parse_args()
    # This is the beef: once the arguments are parsed, pass them on
    really_demo(args.something, args.other, message=args.message)

if __name__ == '__main__':
    main()

Observe how when you run the script from the command line, __name__ will be '__main__' and so it will plunge into the main() function which picks apart the command line, then calls some other function -- in this case, real_demo(). Now, if you are calling this code from an already running Python, there is no need really to collect the arguments into a list and pass them to a new process. Just have your Python script load the function you want to call from the script, and call it with your arguments.

In other words, if you are currently doing

 subprocess.call(['demo.py', '--something', 'foo', '--other', value, '--message', 'whatever'])

you can replace the subprocess call with

 from demo import real_demo
 real_demo('foo', value, message='whatever')

Notice how you are bypassing the main() function and all the ugly command-line parsing, and simply calling another Python function. (Pay attention to the order and names of the arguments; they may be quite different from what the command-line parser accepts.) The fact that it is defined in a different file is a minor detail which import handles for you, and the fact that the file contains other functions is something you can ignore (or perhaps exploit more fully if, for example, you want to access internal functions which are not exposed via the command-line interface in a way which is convenient for you).

As an optimization, Python won't import something twice, so you really need to make sure the functionality you need is not run when you import it. Commonly, you import once, at the beginning of your script (though technically you can do it inside the def which needs it, for example, if there is only one place in your code which depends on the import) and then you call the functions you got from the import as many or as few times as you need them.

This is a lightning recap of a very common question. If this doesn't get you started in the right direction, you should be able to find many existing questions on Stack Overflow about various aspects of this refactoring task.

🌐
Quora
quora.com › How-do-you-pass-command-line-arguments-to-a-Python-script-using-the-subprocess-module
How to pass command line arguments to a Python script using the subprocess module - Quora
Answer: You can very well use the advantage of the builtin module sys and the attribute argv , which has enough capabalities to pass the command line arguments to the module . PFB the example..