将变量传递给子进程调用

时间:2014-03-19 12:19:45

标签: python subprocess

我正在尝试从文件中删除文件的前n行,我计算n并将该值赋给myvariable

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

我从子进程导入了调用。但我在myvariable上遇到语法错误。

1 个答案:

答案 0 :(得分:5)

这里有两件事是错的:

  1. 你的字符串连接语法都错了;这不是有效的Python。你可能想要使用类似的东西:

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

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

    使用字符串格式在这里更具可读性:

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

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

  2. 您需要告诉subprocess.call()通过shell运行该命令,因为您使用的是>>,这是一个仅限shell的功能:

    call(command, shell=True)