我无法使用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')
......考虑到上面的输出,我不认为这是问题,但不知何故仍然发现自己提到它了!
答案 0 :(得分:1)
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)