Python subprocess Popen 不运行命令

2024-04-29 06:54:41 发布

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

我试图使用subprocess.Popen()在我的脚本中运行一个命令。代码是:

output = Popen(["hrun DAR_MeasLogDump " + log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE, executable="/bin/csh", cwd=cwdir, encoding='utf-8')

当我打印输出时,它打印的是创建的shell输出,而不是列表中的实际命令。我试着摆脱executable='/bin/csh',但波本根本就不跑。在

我也试过使用subprocess.communicate(),但也没用。我还可以得到shell输出,而不是实际的命令运行。在

由于安全问题,我希望完全避免使用shell=True。在

编辑:在许多不同的尝试中,“人权署”并没有被重新编码hrun”是一个正在被调用的Pearl脚本,DAR_MeasLogDump是操作,log_file_name是脚本将调用其操作的文件。是否需要进行任何设置或配置才能识别“hrun”?在


Tags: name命令脚本logbinshellfilesubprocess
3条回答

您正在创建subprocess.Popen的实例,但没有执行它。在

你应该试试:

p = Popen(["hrun", "DAR_MeasLogDump ", log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE, cwd=cwdir, encoding='utf-8')

out, err = p.communicate()  # This will get you output

如果不使用shell=True,然后使用executableshould not be required,则应将参数作为序列传递。在

请注意,如果您没有使用Popen中的高级功能,doc建议您使用^{}

^{pr2}$

在这里,指定一个奇数shell和一个显式的cwd似乎完全不合适(假设{}被定义到当前目录)。在

如果subprocess的第一个参数是一个列表,noshell就涉及了。在

result = subprocess.run(["hrun", "DAR_MeasLogDump", log_file_name],
    stdout=subprocess.PIPE, stderr = subprocess.PIPE,
    universal_newlines=True, check=True)
output = result.stdout

如果您需要在Python的旧版本下运行,可以使用check_output而不是{}。在

您通常希望避免Popen,除非您需要做一些高级包装函数不能做的事情。在

尝试:

output = Popen(["-c", "hrun DAR_MeasLogDump " +log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE, executable="/bin/csh", cwd=cwdir, encoding='utf-8')

csh应为-c "full command here"。如果没有-c,我想它只是尝试将其作为文件打开。在

相关问题 更多 >