在python中将多个变量传递给os.system

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22101931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:13:58  来源:igfitidea点击:

passing more than one variables to os.system in python

pythonos.system

提问by hamed

I want to pass two variables to the os.system() for example listing files in different format in specific directory like (ls -l testdirectory) in which both a switch and test directory are variable. I know for single variable this one works:

我想将两个变量传递给 os.system() 例如在特定目录中列出不同格式的文件,如 (ls -l testdirectory) 其中开关和测试目录都是可变的。我知道对于单个变量,这个是有效的:

option=l os.sytem('ls -%s' option)

option=l os.sytem('ls -%s' option)

but I dont know how to pass two variables?

但我不知道如何传递两个变量?

回答by Joran Beasley

you are asking about string formating (since os.systemtakes a string, not a list of arguments)

您正在询问字符串格式(因为os.system需要一个字符串,而不是参数列表)

cmd = "ls -{0} -{1}".format(var1,var2)
#or cmd = "{0} -{1} -{2}".format("ls","l","a")
os.system(cmd)

or

或者

cmd = "ls -%s -%s"%(var1,var2)

or

或者

cmd = "ls -"+var1+" -"+var2

回答by Malvolio

This, for example, works:

例如,这有效:

os.system('%s %s' % ('ls', '-l'))