繁体   English   中英

shell命令在Python中失败并显示subprocess.call()

[英]shell command fails with subprocess.call() in Python

我无法使用subprocess.call()从python脚本运行shell命令。 如果我将python输出复制并粘贴到外壳中,则下面的测试有效,但是当我通过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'

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

我在这里和Google进行了广泛搜索,一些帖子建议将参数转换为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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM