向subprocess.Popen()的“executable”参数传递参数

2024-05-15 00:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

subprocess.Popen()允许通过“executable”参数传递您选择的shell。
我已经选择通过“/bin/tcsh”,我不希望tcsh读取我的~/.cshrc
tcsh手册上说我需要通过-f/bin/tcsh来完成这项工作。

如何让Popen使用-f选项执行/bin/tcsh?

import subprocess

cmd = ["echo hi"]
print cmd

proc = subprocess.Popen(cmd, shell=False,  executable="/bin/tcsh", stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()

for line in proc.stdout:
    print("stdout: " + line.rstrip())

for line in proc.stderr:
    print("stderr: " + line.rstrip())

print return_code

Tags: cmdreturnbinstderrstdoutlinecodeproc
2条回答

让你的生活更轻松:

subprocess.Popen(['/bin/tcsh', '-f', '-c', 'echo hi'],
    shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

我不明白您的问题“将参数传递给子进程可执行文件”的标题与其他问题有什么关系,特别是“我希望tcsh不要读取我的~/.cshrc”

但是-我知道你没有正确使用你的Popen。

您的命令应该是列表或字符串,而不是1个字符串的列表。

所以cmd = ["echo hi"]应该是cmd = "echo hi"或者cmd = ["echo", "hi"]

然后,根据它是字符串还是列表,您需要将shell值设置为TrueFalseTrue如果是字符串,False如果是列表。


“传递”参数是函数的一个术语,使用Popen或subprocess module与函数不同,虽然它们是函数,但实际上是用它们运行命令,而不是传统意义上的传递参数,因此,如果要使用'-f'运行进程,只需将'-f'添加到要使用其运行命令的字符串或列表中。


要把所有的事情放在一起,你应该做如下的事情:

proc = subprocess.Popen('/bin/tcsh -f -c "echo hi"', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

相关问题 更多 >

    热门问题