Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
語(yǔ)法:
child_process.exec(command[, options][, callback])
例子:
hell腳本是一個(gè)命令語(yǔ)言,面向的是操作系統(tǒng)執(zhí)行。如果寫過(guò)shell腳本的話,應(yīng)該體會(huì)過(guò)編寫過(guò)程的痛苦。因?yàn)閟hell并不是一個(gè)編程語(yǔ)言,并不支持常見(jiàn)的數(shù)組,JSON等數(shù)據(jù)結(jié)構(gòu),也不支持面向?qū)ο缶幊痰拈_發(fā)方法,因此對(duì)開發(fā)人員很不友好。
目前針對(duì)這種情況,大家一般會(huì)用shell調(diào)用node執(zhí)行JS腳本,真正的處理邏輯放在JS腳本中處理。現(xiàn)在谷歌推出了 ZX NPM包,它能夠用JS編寫shell腳本。
那如何使用呢?
npm install -g zx
安裝完后,在終端中輸入 zx 命令檢查安裝是否成功。
新建zx腳本文件:test.mjs
#!/usr/bin/env zx
const branch=await $`git branch --show-current`
console.log(`Current branch: ${branch}`)
第一行是指定腳本的執(zhí)行器。
$ 是內(nèi)置的函數(shù),能夠執(zhí)行命令并配合 await 返回執(zhí)行結(jié)果。其他的寫法都和JS毫無(wú)差別。
zx ./test.mjs
或者:
chmod +x ./test.mjs
./test.mjs
控制臺(tái)就會(huì)輸出當(dāng)前的分支。
上面只是小試牛刀,zx 的強(qiáng)大遠(yuǎn)不止如此。由于 zx 在內(nèi)部實(shí)現(xiàn)了 Bash 的解釋器,所以可以執(zhí)行全部的shell命令。另外 zx 還內(nèi)置很多nodejs模塊,比如 fs, os,fetch等。所以可以直接在腳本中使用這些模塊。
另外作為TS編寫的庫(kù),全部的JS語(yǔ)法都能夠支持。包括但不限于 數(shù)組,Promise,class等。
下面再舉一個(gè)例子:
let resp=await fetch('http://wttr.in')
if (resp.ok) {
console.log(await resp.text())
}
let hosts=[...]
await Promise.all(hosts.map(host=>
$`rsync -azP ./src ${host}:/var/www`
))
try {
await $`exit 1`
} catch (p) {
console.log(`Exit code: ${p.exitCode}`)
console.log(`Error: ${p.stderr}`)
}
總結(jié)一下,zx 的最大優(yōu)點(diǎn)是結(jié)合了Bash和JavaScript,解決了shell腳本復(fù)雜邏輯編程的問(wèn)題。同時(shí)也讓對(duì)shell不熟悉的開發(fā)者也能用JS完成shell腳本的開發(fā),而且更加靈活高效。
如果你還有更多問(wèn)題,可以參考NPM倉(cāng)庫(kù) zx 包的介紹,或者訪問(wèn)其github地址。
歡迎幫忙點(diǎn)贊,評(píng)論,轉(zhuǎn)發(fā)~
help(os.system)
#os.system(command):該方法在調(diào)用完shell腳本后,返回一個(gè)16位的二進(jìn)制數(shù),
#低位為殺死所調(diào)用腳本的信號(hào)號(hào)碼,高位為腳本的退出狀態(tài)碼,
#即腳本中exit 1的代碼執(zhí)行后,os.system函數(shù)返回值的高位數(shù)則是1,如果低位數(shù)是0的情況下,
#則函數(shù)的返回值是0x0100,換算為十進(jìn)制得到256。
#要獲得os.system的正確返回值,可以使用位移運(yùn)算(將返回值右移8位)還原返回值:
>>> import os
>>> os.system("./test.sh")
hello python!
hello world!
256
>>> n>>8
1
help(os.system)
#os.popen(command):這種調(diào)用方式是通過(guò)管道的方式來(lái)實(shí)現(xiàn),函數(shù)返回一個(gè)file對(duì)象,
#里面的內(nèi)容是腳本輸出的內(nèi)容(可簡(jiǎn)單理解為echo輸出的內(nèi)容),使用os.popen調(diào)用test.sh的情況
>> import os
>>> os.popen("./test.sh")
<open file './test.sh', mode 'r' at 0x7f6cbbbee4b0>
>>> f=os.popen("./test.sh")
>>> f
<open file './test.sh', mode 'r' at 0x7f6cbbbee540>
>>> f.readlines()
['hello python!\n', 'hello world!\n']
(1)commands.getstatusoutput(cmd),其以字符串的形式返回的是輸出結(jié)果和狀態(tài)碼,即(status,output)。
(2)commands.getoutput(cmd),返回cmd的輸出結(jié)果。
(3)commands.getstatus(file),返回ls -l file的執(zhí)行結(jié)果字符串,調(diào)用了getoutput,不建議使用此方法
subprocess模塊,允許創(chuàng)建很多子進(jìn)程,創(chuàng)建的時(shí)候能指定子進(jìn)程和子進(jìn)程的輸入、輸出、錯(cuò)誤輸出管道,執(zhí)行后能獲取輸出結(jié)果和執(zhí)行狀態(tài)。
(1)subprocess.run():python3.5中新增的函數(shù), 執(zhí)行指定的命令, 等待命令執(zhí)行完成后返回一個(gè)包含執(zhí)行結(jié)果的CompletedProcess類的實(shí)例。
(2)subprocess.call():執(zhí)行指定的命令, 返回命令執(zhí)行狀態(tài), 功能類似os.system(cmd)。
(3)subprocess.check_call():python2.5中新增的函數(shù), 執(zhí)行指定的命令, 如果執(zhí)行成功則返回狀態(tài)碼, 否則拋出異常。
說(shuō)明:subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
args:表示shell指令,若以字符串形式給出shell指令,如"ls -l “則需要使shell=Ture。否則默認(rèn)已數(shù)組形式表示shell變量,如"ls”,"-l"。
當(dāng)使用比較復(fù)雜的shell語(yǔ)句時(shí),可以先使用shlex模塊的shlex.split()方法來(lái)幫助格式化命令,然后在傳遞給run()方法或Popen。
# Stubs for subprocess
# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub
from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text
_FILE=Union[None, int, IO[Any]]
_TXT=Union[bytes, Text]
_CMD=Union[_TXT, Sequence[_TXT]]
_ENV=Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]
# Same args as Popen.__init__
def call(args: _CMD,
bufsize: int=...,
executable: _TXT=...,
stdin: _FILE=...,
stdout: _FILE=...,
stderr: _FILE=...,
preexec_fn: Callable[[], Any]=...,
close_fds: bool=...,
shell: bool=...,
cwd: _TXT=...,
env: _ENV=...,
universal_newlines: bool=...,
startupinfo: Any=...,
creationflags: int=...) -> int: ...
def check_call(args: _CMD,
bufsize: int=...,
executable: _TXT=...,
stdin: _FILE=...,
stdout: _FILE=...,
stderr: _FILE=...,
preexec_fn: Callable[[], Any]=...,
close_fds: bool=...,
shell: bool=...,
cwd: _TXT=...,
env: _ENV=...,
universal_newlines: bool=...,
startupinfo: Any=...,
creationflags: int=...) -> int: ...
# Same args as Popen.__init__ except for stdout
def check_output(args: _CMD,
bufsize: int=...,
executable: _TXT=...,
stdin: _FILE=...,
stderr: _FILE=...,
preexec_fn: Callable[[], Any]=...,
close_fds: bool=...,
shell: bool=...,
cwd: _TXT=...,
env: _ENV=...,
universal_newlines: bool=...,
startupinfo: Any=...,
creationflags: int=...) -> bytes: ...
PIPE=... # type: int
STDOUT=... # type: int
class CalledProcessError(Exception):
returncode=0
# morally: _CMD
cmd=... # type: Any
# morally: Optional[bytes]
output=... # type: Any
def __init__(self,
returncode: int,
cmd: _CMD,
output: Optional[bytes]=...) -> None: ...
class Popen:
stdin=... # type: Optional[IO[Any]]
stdout=... # type: Optional[IO[Any]]
stderr=... # type: Optional[IO[Any]]
pid=0
returncode=0
def __init__(self,
args: _CMD,
bufsize: int=...,
executable: Optional[_TXT]=...,
stdin: Optional[_FILE]=...,
stdout: Optional[_FILE]=...,
stderr: Optional[_FILE]=...,
preexec_fn: Optional[Callable[[], Any]]=...,
close_fds: bool=...,
shell: bool=...,
cwd: Optional[_TXT]=...,
env: Optional[_ENV]=...,
universal_newlines: bool=...,
startupinfo: Optional[Any]=...,
creationflags: int=...) -> None: ...
def poll(self) -> int: ...
def wait(self) -> int: ...
# morally: -> Tuple[Optional[bytes], Optional[bytes]]
def communicate(self, input: Optional[_TXT]=...) -> Tuple[Any, Any]: ...
def send_signal(self, signal: int) -> None: ...
def terminate(self) -> None: ...
def kill(self) -> None: ...
def __enter__(self) -> 'Popen': ...
def __exit__(self, type, value, traceback) -> bool: ...
# Windows-only: STARTUPINFO etc.
STD_INPUT_HANDLE=... # type: Any
STD_OUTPUT_HANDLE=... # type: Any
STD_ERROR_HANDLE=... # type: Any
SW_HIDE=... # type: Any
STARTF_USESTDHANDLES=... # type: Any
STARTF_USESHOWWINDOW=... # type: Any
CREATE_NEW_CONSOLE=... # type: Any
CREATE_NEW_PROCESS_GROUP=... # type: Any
https://www.jb51.net/article/186301.htm
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。