使用带有LC_ALL的Python subprocess.check_output()作为第一个参数

时间:2017-01-21 18:49:40

标签: python-2.7 subprocess

从Python脚本

我想调用一些外部程序并在脚本中使用它们的输出。现在我发现这个脚本在我的本地系统上运行,但在使用另一种语言的另一个脚本上遇到问题。因此,我不想用不同的语言检查输出,而是想用指定的“LC_ALL = en_US.utf8”作为第一个参数来调用这些程序。但似乎子进程不喜欢这样:

Traceback (most recent call last):
  File "./serverwatch.py", line 22, in <module>
    uptimedata = subprocess.check_output([lc, "/bin/uptime"])
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

当我运行脚本时,我得到:

ListCell

我知道subprocess.check_output()希望第一个参数成为要调用的命令。那么如何使用更改的LC运行命令?

这是Debian Wheezy上的Python 2.7.3。另一个系统运行相同的版本。

1 个答案:

答案 0 :(得分:0)

通过bash执行命令:

>>> lc = "LC_ALL=en_US.utf8"
>>> command = ["/usr/bin/bash", "-c", "%s /bin/uptime" % lc]
>>> command
['/usr/bin/bash', '-c', 'LC_ALL=en_US.utf8 /bin/uptime']
>>> uptimedata = subprocess.check_output(command)
>>> uptimedata
b' 13:26:01 up 17:43,  1 user,  load average: 0.36, 0.41, 0.44\n'
>>>