Passing arguments to subprocess.run from list

huangapple go评论49阅读模式
英文:

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']])

huangapple
  • 本文由 发表于 2023年6月6日 03:45:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定