如何在python中的shell命令中使用变量值?

我有一个shell命令,该命令使用从Python脚本中调用的一些参数:

cmd = 'sysbench --test=cpu --cpu-max-prime=20000 --num-threads=2 run > cpu_sysbench.txt'

现在,我想将-cpu-max-prime值定义为变量并使用它:

prime_numbers = "20000"
cmd = 'sysbench --test=cpu --cpu-max-prime=$prime_numbers --num-threads=2 run'

但是当我运行它时,我看到一些语法错误:

ASD52113144 回答:如何在python中的shell命令中使用变量值?

尝试:

cmd = f'sysbench --test=cpu --cpu-max-prime={prime_numbers} --num-threads=2 run'

这称为f字符串,这是在Python> = 3.6中格式化字符串的简单方法。当然,您也可以只使用字符串连接或其他方法,这完全不是运行shell命令所特有的。

,

使用import io.reactivex.schedulers.TestScheduler val testScheduler = TestScheduler() @Before fun before() { //you create your SearchImpl class here and use testScheduler to replace real schedulers inside it } @Test fun loadItems_WhenDataIsAvailable() { `when`(api.getFilms()).thenReturn(Observable.just(filmRequestFacke())) searchImpl.getfilms(callback) testScheduler.triggerActions() //Triggers any actions that have not yet been triggered and that are scheduled to be triggered at or before this Scheduler's present time. verify(callback)?.onResponseSearchFilm(fackeFilms()) }

例如:

str.format
,

完全不使用字符串格式。构建一个由命令名称和参数作为单独元素的 list ,以与subprocess.Popen(或其包装函数之一)一起使用。

prime_numbers = "20000"
cmd = [
    'sysbench','--test=cpu','--cpu-max-prime',prime_numbers,'--num-threads=2','run'
]

with open("cpu_sysbench.txt","w") as f:
    subprocess.run(cmd,stdout=f)
    # or subprocess.call(cmd,stdout=f) in older Python 3.x

更新:要合并grep命令,请使用两个子进程,这些子进程的标准输入和标准输出结合在一起。

with open("cpu_sysbench.txt","w") as f:

    p1 = subprocess.Popen(cmd,stdout=subprocess.PIPE)
    # grep + cut can almost always be replaced by a single awk
    subprocess.call(['awk','-F',':','/total time:/ { print $2 }'],stdin=p1.stdout,stdout=f)
本文链接:https://www.f2er.com/3102704.html

大家都在问