導航:首頁 > 程序命令 > python執行shell命令

python執行shell命令

發布時間:2022-10-23 05:19:41

『壹』 python中怎麼運行shell腳本

python中怎麼運行shell腳本?
system()
其中最後一個0是這個命令的返回值,為0表示命令執行成功。使用system無法將執行的結果保存起來。
popen()
獲取命令執行的結果,但是沒有命令的執行狀態,這樣可以將獲取的結果保存起來放到pst中。
commands
可以很方便的取得命令的輸出(包括標准和錯誤輸出)和執行狀態位。
commands.getoutput('ls')這個方法只返回執行結果result不返回狀態。
在python中調用shell腳本
hello.sh
下面的512是返回的狀態碼,如果eixt 0時則返回的是0.
shell腳本使用python腳本的參數
寫一個hello.sh腳本,需要傳入兩個參數:
執行結果如下:
在python腳本中調用shell腳本,並傳入參數,注意參數前後要有空格
執行python腳本
相關推薦:《Python教程》以上就是小編分享的關於python中怎麼運行shell腳本的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!

『貳』 python執行shell命令和java執行shell命令的區別

沒區別。。。
因為都是調用的同一個東西,能有區別嗎?

『叄』 python中的shell提示符是什麼意思

命令行的shell直接輸入你要輸入的東西就行。

Shell 循環

啟動 shell 時,它會立刻展示命令提示符並等待輸入。在接收到命令並執行完畢(細節會在後面講到)後,shell 會再次回到等待循環,准備接收下一條命令。

在shell.py中,我們通過主函數調用shell_loop()函數,來啟動循環。代碼如下:

然後在shell_loop()函數中,使用status標志來表示循環是否應該繼續。在循環開始時,shell 將立即顯示命令提示符,並等待輸入。

(3)python執行shell命令擴展閱讀

用戶在 shell 中鍵入命令並按下回車時,輸入的命令是一條長長的字元串,其中包含了命令名以及參數。因此,我們必須將其切分(將字元串拆分成多個 token)。

字元串切分乍一看很簡單。我們可能會使用cmd.split()根據空格來分割輸入的命令。對於形如ls -a my_folder的命令是奏效的,因為cmd.split()會將其拆分為一個列表 —['ls', '-a', 'my_folder』],這樣我們使用起來就比較容易了。

但是,某些情況下,某些參數會帶有單引號或者雙引號,比如echo "Hello World」或者echo 'Hello World』。如果我們使用cmd.split(), 將會得到一個包含三個 token 的列表 —['echo', '"Hello', 'World」』],而不是包含兩個 token 的列表 —['echo', 'Hello World』]。

『肆』 如何使用python執行遠程shell腳本

最近有個需求就是頁面上執行shell命令,第一想到的就是os.system,

代碼如下:
os.system('cat /proc/cpuinfo')

但是發現頁面上列印的命令執行結果 0或者1,當然不滿足需求了。

嘗試第二種方案 os.popen()

代碼如下:
output = os.popen('cat /proc/cpuinfo')
print output.read()

通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是無法讀取程序執行的返回值)

嘗試第三種方案 commands.getstatusoutput() 一個方法就可以獲得到返回值和輸出,非常好用。

代碼如下:
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output

Python Document 中給的一個例子,

代碼如下:
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

『伍』 我希望通過Python腳本實現多次執行shell命令

python腳本實現多次循環執行shell命令有三種方法,代碼如下:

#方法一
os.system
importos
i=0
whileTrue:
i=i+1
os.system("tcpreplay-ibond0-M5-l1oracle_request_response.cap")
print"+++++++++++++++++++++++++++++++"
print"times:",i
time.sleep(5)

#方法二
os.popen
importos
i=0
whileTrue:
i=i+1
printos.popen("tcpreplay-ibond0-M5-l1oracle_request_response.cap").read()
print"+++++++++++++++++++++++++++++++"
print"times:",i
time.sleep(60)

#方法三
output=Popen("xxx",shell=True).communicate()[0]
importos
fromsubprocessimport*
i=0
whileTrue:
i=i+1
output=Popen("tcpreplay-ibond0-M5-l1oracle/*",shell=True).communicate()[0]
print"+++++++++++++++++++++++++++++++"
print"times:",i
time.sleep(60)

『陸』 什麼是python shell 命令

python shell不是特指某一項命令,而是一種命令行環境。可以在shell裡面導包、執行語句,常見的有 ipython環境,比python自帶的shell要好得多。安裝方式:pip install ipython

『柒』 python shell怎麼使用

Python 中執行 Shell 命令有多種方法,stackoverflow 上有對這些方法進行比較的討論,Calling an external command in Python 指出使用subprocess模塊來實現更優。因此,本文說明如何使用subprocess模塊來實現 Shell 腳本的功能。
subprocess模塊提供多種方法來實現執行 Linux 的命令,例如subprocess.call()方法,subprocess.check_call()方法,等。這些方法都是對Popen類的封裝,故本文著重講述Popen類的使用。

執行 Shell 命令
可以通過向Popen()傳遞需要執行的命令來創建一個Popen對象,這樣,便會創建一個子進程來執行命令。例如:

child = subprocess.Popen(["ping","-c","5","leehao.me"])
1
上面的代碼會創建一個子進程來執行ping -c 5 leehao.me命令,這個命令採用列表的形式傳遞給Popen()方法。如果我們想直接採用ping -c 5 leehao.me字元串形式,可以添加shell=True來實現:

child = subprocess.Popen("ping -c 5 leehao.me", shell=True)
1
官方文檔指出由於安全原因故不建議使用shell=True,詳細說明可以參考官方文檔的描述。

等待子進程執行
子進程執行命令後,主進程並不會等待子進程執行。為了讓主進程等待子進程執行結束,需要顯示調用Popen.wait()方法。例如:

child = subprocess.Popen(["ping","-c","5","leehao.me"])
child.wait()
print 'parent finish'
1
2
3
這樣,主進程會等待子進程執行ping命令完畢後,才會列印出parent finish的輸出。

獲取執行結果
為了獲取Popen()子進程的輸出,可以使用Popen.communicate()方法,例如:

def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout

subprocess_cmd('echo leehao.me; echo www.leehao.me')
1
2
3
4
5
6
輸出:

leehao.me
www.leehao.me

process.communicate()方法可以實現主進程與子進程的通信。主進程可以通過它向子進程發送數據,也可以讀取子進程的輸出的數據。上面的例子中,我們在創建Popen對象時指定stdout=subprocess.PIPE,這樣主進程便可以讀取子進程的輸出。
communicate()方法返回一個元組:(stdoutdata, stderrdata),process.communicate()[0]即獲取子進程的標准輸出。
需要指出的是,調用communicate()方法後,主進程也會等待子進程執行完畢。
上面的例子中,子進程向標准輸出列印兩個字元串,主進程接收到了這些輸出,並列印出來。

『捌』 如何python 中運行scapy shell

啟用shell
可以使用如下命令啟用shell
[python] view plain
scrapy shell <url>
其中<url>就是你想抓取的頁面url

使用shell
Scrapy shell可以看成是一個內置了幾個有用的功能函數的python控制台程序。

功能函數
shelp() - 輸出一系列可用的對象和函數
fetch(request_or_url)-從給定的url或既有的request請求對象重新生成response對象,並更新原有的相關對象
view(response)-使用瀏覽器打開原有的response對象(換句話說就是html頁面)
Scrapy 對象
使用Scrapy shell下載指定頁面的時候,會生成一些可用的對象,比如Response對象和Selector對象(Html和XML均適用)
這些可用的對象有:

crawler - 當前的Crawler對象
spider
request - 最後獲取頁面的請求對象
response - 一個包含最後獲取頁面的響應對象
sel - 最新下載頁面的Selector對象
settings - 當前的Scrapy settings
Scrapy shell例子
以我的個人博客作為測試:http://blog.csdn.net/php_fly
首先,我們啟動shell
[python] view plain
scrapy shell http://blog.csdn.net/php_fly --nolog
以上命令執行後,會使用Scrapy downloader下載指定url的頁面數據,並且列印出可用的對象和函數列表

[python] view plain
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x0000000002AEF7B8>
[s] item {}
[s] request <GET http://blog.csdn.net/php_fly>
[s] response <200 http://blog.csdn.net/php_fly>
[s] sel <Selector xpath=None data=u'<html xmlns="http://www.w3.org/1999/xhtm'>
[s] settings <CrawlerSettings mole=None>
[s] spider <Spider 'default' at 0x4cdb940>
[s] Useful shortcuts:
[s] shelp() Shell help (print this help)
[s] fetch(req_or_url) Fetch request (or URL) and update local objects
[s] view(response) View response in a browser
獲取曾是土木人博客的文章列表超鏈接
[python] view plain
In [9]: sel.xpath("//span[@class='link_title']/a/@href").extract()
Out[9]:
[u'/php_fly/article/details/19364913',
u'/php_fly/article/details/18155421',
u'/php_fly/article/details/17629021',
u'/php_fly/article/details/17619689',
u'/php_fly/article/details/17386163',
u'/php_fly/article/details/17266889',
u'/php_fly/article/details/17172381',
u'/php_fly/article/details/17171985',
u'/php_fly/article/details/17145295',
u'/php_fly/article/details/17122961',
u'/php_fly/article/details/17117891',
u'/php_fly/article/details/14533681',
u'/php_fly/article/details/13162011',
u'/php_fly/article/details/12658277',
u'/php_fly/article/details/12528391',
u'/php_fly/article/details/12421473',
u'/php_fly/article/details/12319943',
u'/php_fly/article/details/12293587',
u'/php_fly/article/details/12293381',
u'/php_fly/article/details/12289803']
修改scrapy shell的請求方式:

[python] view plain
>>> request = request.replace(method="POST")
>>> fetch(request)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
...

從Spider中調用Scrapy shell
在爬蟲運行過程中,有時需要檢查某個響應是否是你所期望的。
這個需求可以通過scrapy.shell.inspect_response函數進行實現
以下是一個關於如何從spider中調用scrapy shell的例子

[python] view plain
from scrapy.spider import Spider

class MySpider(Spider):
name = "myspider"
start_urls = [
"http://example.com",
"http://example.org",
"http://example.net",
]

def parse(self, response):
# We want to inspect one specific response.
if ".org" in response.url:
from scrapy.shell import inspect_response
inspect_response(response)

# Rest of parsing code.
當你啟動爬蟲的時候,控制台將列印出類似如下的信息
[python] view plain
2014-02-20 17:48:31-0400 [myspider] DEBUG: Crawled (200) <GET http://example.com> (referer: None)
2014-02-20 17:48:31-0400 [myspider] DEBUG: Crawled (200) <GET http://example.org> (referer: None)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
...
>>> response.url
'http://example.org'
注意:當Scrapy engine被scrapy shell佔用的時候,Scrapy shell中的fetch函數是無法使用的。 然而,當你退出Scrapy shell的時候,蜘蛛將從停止的地方繼續爬行

『玖』 python shell中怎麼重復執行命令

有三種方法:
1、os.system

import os

i = 0

while True:

i = i + 1

os.system("tcpreplay -ibond0 -M 5 -l 1
oracle_request_response.cap")

print"+++++++++++++++++++++++++++++++"

print"times:" ,i

time.sleep(5)

2、os.popen

import os

i = 0

while True:

i = i + 1

print os.popen("tcpreplay -ibond0 -M 5 -l 1
oracle_request_response.cap").read()

print"+++++++++++++++++++++++++++++++"

print"times:" ,i

time.sleep(60)

3、output = Popen("xxx",shell
= True).communicate()[0]

import os

from subprocess import *

i = 0

while True:

i = i + 1

output = Popen("tcpreplay -ibond0 -M 5 -l 1
oracle/*",shell = True).communicate()[0]

print"+++++++++++++++++++++++++++++++"

print"times:" ,i

time.sleep(60)

『拾』 請教python如何執行shell管道命令

Python執行Linux系統命令,即在Python腳本中調用Shell命令,具體有以下四種方法:
1、os.system
//僅僅在一個子終端運行系統命令,而不能獲取命令執行後的返回信息
system(command) -> exit_status
Execute the command (a string) in a subshell.
//如果再命令行下執行,結果直接列印出來:
>>> os.system('ls')
04101419778.CHM bash document media py-django video
11.wmv books downloads Pictures python
all-20061022 Desktop Examples project tools
2、os.popen
//該方法不但執行命令還返回執行後的信息對象
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
3、使用模塊 subprocess
>>> import subprocess
>>> subprocess.call(["cmd", "arg1", "arg2"],shell=True)
//獲取返回和輸出:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
4、使用模塊 commands

>>> import commands
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
>>> commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
>>>
>>> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')

閱讀全文

與python執行shell命令相關的資料

熱點內容
病歷轉pdf 瀏覽:833
雲伺服器配硬體 瀏覽:974
伺服器10k什麼意思 瀏覽:21
pdfeditor漢化 瀏覽:884
新科學pdf 瀏覽:746
現在還有c語言編譯嗎 瀏覽:674
哪裡買到單片機 瀏覽:480
linux文件打開數量 瀏覽:510
編譯原理中什麼是l屬性文法 瀏覽:369
硬碟加密時出現的問題 瀏覽:61
如何退域命令 瀏覽:108
看書的app哪裡看 瀏覽:291
伺服器怎麼調大 瀏覽:3
android天氣apijson 瀏覽:984
為什麼創建id會出現伺服器錯誤 瀏覽:837
代碼中有不必編譯的單詞嗎 瀏覽:563
鉤子與資料庫編程 瀏覽:563
安卓光遇錄歌怎麼設置 瀏覽:485
虛擬機怎麼和雲伺服器搭建集群 瀏覽:896
python倒計時代碼turtle 瀏覽:492