簡體   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