Skip to main content
 首页 » 编程设计

python之shell 命令因 Python 中的 subprocess.call() 而失败

2025年05月04日13del

我无法使用 subprocess.call() 从 python 脚本运行 shell 命令。如果我复制 python 输出并粘贴到 shell 中,但当我通过 subprocess.call() 调用命令时,下面的测试有效。有人能解释一下我的错误/想法吗?我刚开始编程,认为这是“只见树木不见森林”的事情,还有其他关于此的帖子,但我无法将它们应用于我的问题。

我认为 shell 脚本没有得到它的参数。我已经设置了 shell=True 并尝试将 ' 和 "args 与空格分开。

import subprocess as s 
 
fromCall = 'MB7UZ-1' 
toCall = 'APRS' 
path = 'via WIDE1-1' 
ax25Port = 'aprs' 
command = "/sbin/beacon" 
packet = ":Test Beacon 4" 
 
command_args = "-c '{0}' -d '{1} {2}' -s {3} '{4}'".format(fromCall, toCall, path, ax25Port, packet) 
 
s.call([command, command_args], shell=True) 
print repr(command_args) 

将以下内容打印到控制台

/sbin/beacon -c MB7UZ-1 -d 'APRS via WIDE1-1' -s aprs ':Test Beacon 4' 

如果我复制整行并粘贴回 shell,/sbin/beacon 程序将按预期工作。

我在这里和谷歌进行了广泛的搜索,一些帖子建议将参数转换为 UTF-8 ...

Python 2.7.3 (default, Feb 27 2013, 13:38:49) 
[GCC 4.7.2 20120921 (Red Hat 4.7.2-2)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import locale ; locale.getdefaultlocale() 
('en_US', 'UTF-8') 

...鉴于上面的输出,我不认为这是问题所在,但不知何故我还是发现自己提到了它!

请您参考如下方法:

s.call 的参数应该如下所示:[command, "arg1", "arg2", "arg3", ...],你重新传递 [command, "arg1 arg2 arg3"] 所以 /sbin/beacon 只得到一个参数,即:

-c MB7UZ-1 -d 'APRS via WIDE1-1' -s aprs ':Test Beacon 4' 

您有两个选择,最好的一个是拆分参数。像这样的东西:

import subprocess as s 
 
fromCall = 'MB7UZ-1' 
toCall = 'APRS' 
path = 'via WIDE1-1' 
ax25Port = 'aprs' 
command = "/sbin/beacon" 
packet = ":Test Beacon 4" 
 
command = ["/sbin/beacon", "-c", fromCall, "-d", " ".join((toCall, path)), "-s", 
           ax25Port, packet] 
s.call(command) 

或者我不太喜欢的选项,将单个字符串传递给 s.call 并让 shell 为您拆分参数。只有使用 shell=True 才能执行此操作。

import subprocess as s 
 
fromCall = 'MB7UZ-1' 
toCall = 'APRS' 
path = 'via WIDE1-1' 
ax25Port = 'aprs' 
command = "/sbin/beacon" 
packet = ":Test Beacon 4" 
 
command = command + " -c '{0}' -d '{1} {2}' -s {3} '{4}'".format(fromCall, toCall, path, ax25Port, packet) 
 
s.call(command, shell=True) 
print repr(command)