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 OverflowTry 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.
Try to add commas between your list items:
subprocess.call(['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, \
'-u' ,_userid, _username])
subprocess.call takes the same arguments as subprocess.Popen:
argsshould be a string, or a sequence of program arguments.
Edit
To turn all your arguments into strings at once you could you a list comprehension:
args = ['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, \
'-u' ,_userid, _username]
str_args = [ str(x) for x in args ]
How can I pass arguments to subprocess.call or subprocess.run for execution in PS?
Python subprocess arguments - Stack Overflow
How to pass arguments in python subprocess? - Stack Overflow
python - How to pass arguments to subprocess - Stack Overflow
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)As JBernardo mentioned in a comment, separate the "-bufsize 4096" argument into two, "-bufsize", "4096". 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 it directly, otherwise call str(url) to get a string representation.
This is the way to go:
url = 'http://www.whatever.com'
cmd = 'ffplay -vn -nodisp -bufsize 4096 '.split()
subprocess.call(cmd + [str(url)], shell=False)
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:
subprocess.run(["ls", "-l", "--color=auto"])
Here, that would be:
subprocess.run(["python3", "detect_wrong.py", "--source", "overpass.mp4", "--weights", "./my_coco.pt", "--data", "./data/my_coco.yaml"])
However, since you want to run a Python script from Python, I suggest you take a look here: How can I make one python file run another? and, as said there, treat detect_wrong.py as a module, if possible.
Else, you can run it with exec() or, if desperate, with os.system() or subprocess.run()
you can simply pass arguments as entities on the list, like that:
subprocess.run(["python", "--argument=value", "detect_wrong.py"]
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?
Pass arguments as a list, see the very first code example in the docs:
import subprocess
subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3])
If arg3 is not a string; convert it to string before passing to check_call(): arg3 = str(arg3).
subprocess.Popen(['/my/file/path/programname.sh arg1 arg2 %s' % arg3], shell = True).
If you use shell = True the script and its arguments have to be passed as a string. Any other elements in the args sequence will be treated as arguments to the shell.
You can find the complete docs at http://docs.python.org/2/library/subprocess.html#subprocess.Popen.
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.
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.