将变量传递给子进程调用 [英] Passing a variable to a subprocess call

查看:30
本文介绍了将变量传递给子进程调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文件中删除文件的前 n 行,我计算 n 并将该值分配给 myvariable

I'm trying to cut the first n lines of a file off a file, I calculate n and assign that value to myvariable

command = "tail -n +"myvariable" test.txt >> testmod.txt"
call(command)

我已经从子进程导入了调用.但我在 myvariable 处遇到语法错误.

I've imported call from subprocess. But I get a syntax error at myvariable.

推荐答案

这里有两个错误:

  1. 你的字符串连接语法全错了;这不是有效的 Python.您可能想使用以下内容:

  1. Your string concatenation syntax is all wrong; that's not valid Python. You probably wanted to use something like:

command = "tail -n " + str(myvariable) + " test.txt >> testmod.txt"

我假设 myvariable 是一个整数,而不是一个字符串.

where I assume that myvariable is an integer, not a string already.

在这里使用字符串格式会更易读:

Using string formatting would be more readable here:

command = "tail -n {} test.txt >> testmod.txt".format(myvariable)

str.format() 方法将为您将 {} 替换为 myvariable 的字符串版本.

where the str.format() method will replace {} with the string version of myvariable for you.

您需要告诉 subprocess.call() 通过 shell 运行该命令,因为您正在使用 >>,一个仅 shell 的特点:

You need to tell subprocess.call() to run that command through the shell, because you are using >>, a shell-only feature:

call(command, shell=True)

这篇关于将变量传递给子进程调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆