patternpythonModerate
Join argv list with spaces
Viewed 0 times
argvwithjoinspaceslist
Problem
I'm a Python noob. This is the code I'm using:
Is there a more elegant way to do this?
for i in argv[2:]: # argv[1] isn't required by s.py
if ' ' in i:
argv[argv.index(i)] = '"%s"' % i
args = ' '.join(argv[2:])
os.system('s.py '+args)Is there a more elegant way to do this?
Solution
You shouldn't use
This is a lot cleaner. In your version you added quotes around the command line arguments that contained spaces. (Which btw would break spectacularly if the command line arg also contained quote character...) Using
os.system to run commands. You should use subprocess instead, for example:from sys import argv
import subprocess
cmd = 's.py'
args = [cmd] + argv[2:]
subprocess.call(args)This is a lot cleaner. In your version you added quotes around the command line arguments that contained spaces. (Which btw would break spectacularly if the command line arg also contained quote character...) Using
subprocess, you don't need such dirty hacks.Code Snippets
from sys import argv
import subprocess
cmd = 's.py'
args = [cmd] + argv[2:]
subprocess.call(args)Context
StackExchange Code Review Q#62503, answer score: 10
Revisions (0)
No revisions yet.