将参数传递给subprocess.Popen()调用的"可执行文件"参数

4

使用subprocess.Popen()函数,你可以通过"executable"参数指定你想要的shell。
我选择了传递"/bin/tcsh",并且不希望tcsh读取我的~/.cshrc文件。
tcsh手册指出,我需要向/bin/tcsh传递-f参数来实现这一点。

如何让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

你需要使用tcsh有什么特别的原因吗?为什么不能使用/bin/sh呢? - Blender
遗留目的;我需要获取一个 tcsh 脚本。 - Shajid Thiruvathodi
2个回答

5
让生活更轻松:
subprocess.Popen(['/bin/tcsh', '-f', '-c', 'echo hi'],
    shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

0
我不明白你的问题标题“向子进程可执行文件传递参数”与其余部分,特别是“我希望tcsh不要读取我的~/.cshrc”的关系。但是,我知道您没有正确使用Popen。您的cmd应该是列表或字符串,而不是1个字符串的列表。所以,"cmd = ["echo hi"]" 应该是 "cmd = "echo hi"" 或 "cmd = ["echo", "hi"]"。然后,根据它是字符串还是列表,您需要将shell值设置为True或False。如果它是一个字符串,则为True,如果它是一个列表,则为False。
“传递参数”是函数的术语,使用Popen或subprocess模块与函数不同,虽然它们也是函数,但实际上你是在运行一个命令,而不是以传统意义上的方式传递参数给它们。因此,如果你想要使用'-f'运行一个进程,只需将'-f'添加到你想要运行该命令的字符串或列表中即可。
为了整合所有内容,您应该运行类似以下的命令:
proc = subprocess.Popen('/bin/tcsh -f -c "echo hi"', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

然后,根据是字符串还是列表,您需要将shell值设置为True或False-我认为您搞反了。首先,您需要决定是否需要通过shell运行命令(通常不需要)。这将确定您应该如何传递命令。 - Brecht Machiels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接