英文:
Passing arguments to subprocess.run from list
问题
以下是要翻译的内容:
我想将参数传递给一个 rsync
子进程,参数来自一个列表(或字符串),但我找不到任何方法可以在不指定每个列表项的情况下执行此操作。也就是说,这段代码可以工作:
args = ['--progress', '-avh']
subprocess.run(['rsync', args[0], args[1], loaded_prefs['src_dir'], loaded_prefs['dst_dir']])
但这段代码不起作用:
args = '--progress -avh'
subprocess.run(['rsync', args, loaded_prefs['src_dir'], loaded_prefs['dst_dir']])
或者这段代码也不行:
args = ['--progress', '-avh']
subprocess.run(['rsync', ','.join(args), loaded_prefs['dst_dir']])
任何帮助将不胜感激。
英文:
I want to pass arguments to an rsync
subprocess from a list (or string) but can't find any way to do it without specifying each list item. ie this works
args = ['--progress', '-avh']
subprocess.run(['rsync', args[0],args[1],loaded_prefs['src_dir'],loaded_prefs['dst_dir']])
but this doesn't
args = '--progress -avh'
subprocess.run(['rsync', args,loaded_prefs['src_dir'],loaded_prefs['dst_dir']])
or this
args = ['--progress', '-avh']
subprocess.run(['rsync', ','.join(args),loaded_prefs['dst_dir']])
Any help would be much appreciated
答案1
得分: 3
--progress
和 -avh
需要分别作为传递给 subprocess.run()
的列表元素。不要将它们合并成单个字符串。保持为列表,然后用 *
展开该列表。
args = ['--progress', '-avh']
subprocess.run(['rsync', *args, loaded_prefs['src_dir'], loaded_prefs['dst_dir']])
英文:
--progress
and -avh
need to be separate elements of the list you pass to subprocess.run()
. You're combining them into a single string. Keep it as a list, and then spread the list with *
.
args = ['--progress', '-avh']
subprocess.run(['rsync', *args,loaded_prefs['src_dir'],loaded_prefs['dst_dir']])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论