1. python os.system()問題
if not os.path.exists(dst_dir): os.mkdir(dst_dir) print("this DIR %s set up Successful!" % dst_dir)else: print("this DIR %s is exists!" % dst_dir)zip_command = "winrar a %s %s" % (r_name,' '.join(source))# 這個winrar,你在cmd能運行嗎?不能的話就加入絕對路徑print (zip_command)try: os.system(zip_command) print("傷不起!")except Exception as e: print (e) print ("命令執行失敗咯,你懂得!")
2. python sys.path.append('..')括弧里這兩個點是什麼意思
目錄的意思,即代表上一級目錄。
3. python os和sys模塊的區別
os與sys模塊的官方解釋如下:
os: This mole provides a portable way of using operating system dependent functionality.
這個模塊提供了一種方便的使用操作系統函數的方法。
sys: This mole provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
這個模塊可供訪問由解釋器使用或維護的變數和與解釋器進行交互的函數。
總結就是,os模塊負責程序與操作系統的交互,提供了訪問操作系統底層的介面;sys模塊負責程序與python解釋器的交互,提供了一系列的函數和變數,用於操控python的運行時環境。
os 常用方法
os.remove(『path/filename』) 刪除文件
os.rename(oldname, newname) 重命名文件
os.walk() 生成目錄樹下的所有文件名
os.chdir('dirname') 改變目錄
os.mkdir/makedirs('dirname')創建目錄/多層目錄
os.rmdir/removedirs('dirname') 刪除目錄/多層目錄
os.listdir('dirname') 列出指定目錄的文件
os.getcwd() 取得當前工作目錄
os.chmod() 改變目錄許可權
os.path.basename(『path/filename』) 去掉目錄路徑,返迴文件名
os.path.dirname(『path/filename』) 去掉文件名,返回目錄路徑
os.path.join(path1[,path2[,...]]) 將分離的各部分組合成一個路徑名
os.path.split('path') 返回( dirname(), basename())元組
os.path.splitext() 返回 (filename, extension) 元組
os.path.getatime\ctime\mtime 分別返回最近訪問、創建、修改時間
os.path.getsize() 返迴文件大小
os.path.exists() 是否存在
os.path.isabs() 是否為絕對路徑
os.path.isdir() 是否為目錄
os.path.isfile() 是否為文件
sys 常用方法
sys.argv 命令行參數List,第一個元素是程序本身路徑
sys.moles.keys() 返回所有已經導入的模塊列表
sys.exc_info() 獲取當前正在處理的異常類,exc_type、exc_value、exc_traceback當前處理的異常詳細信息
sys.exit(n) 退出程序,正常退出時exit(0)
sys.hexversion 獲取Python解釋程序的版本值,16進制格式如:0x020403F0
sys.version 獲取Python解釋程序的版本信息
sys.maxint 最大的Int值
sys.maxunicode 最大的Unicode值
sys.moles 返回系統導入的模塊欄位,key是模塊名,value是模塊
sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變數的值
sys.platform 返回操作系統平台名稱
sys.stdout 標准輸出
sys.stdin 標准輸入
sys.stderr 錯誤輸出
sys.exc_clear() 用來清除當前線程所出現的當前的或最近的錯誤信息
sys.exec_prefix 返回平台獨立的python文件安裝的位置
sys.byteorder 本地位元組規則的指示器,big-endian平台的值是'big',little-endian平台的值是'little'
sys.right 記錄python版權相關的東西
sys.api_version 解釋器的C的API版本
sys.stdin,sys.stdout,sys.stderr
stdin , stdout , 以及stderr 變數包含與標准I/O 流對應的流對象. 如果需要更好地控制輸出,而print 不能滿足你的要求, 它們就是你所需要的. 你也可以替換它們, 這時候你就可以重定向輸出和輸入到其它設備( device ), 或者以非標準的方式處理它們
我們常用print和raw_input來進行輸入和列印,那麼print 和 raw_input是如何與標准輸入/輸出流建立關系的呢?
其實Python程序的標准輸入/輸出/出錯流定義在sys模塊中,分別 為: sys.stdin,sys.stdout, sys.stderr
下列的程序也可以用來輸入和輸出是一樣的:
import sys
sys.stdout.write('HelloWorld!')
print 'Please enter yourname:',
name=sys.stdin.readline()[:-1]
print 'Hi, %s!' % name
那麼sys.stdin, sys.stdout, stderr到底是什麼呢?我們在Python運行環境中輸入以下代碼:
import sys
for f in (sys.stdin,sys.stdout, sys.stderr): print f
輸出為:
<open file'<stdin>', mode 'r' at 892210>
<open file'<stdout>', mode 'w' at 892270>
<open file'<stderr>', mode 'w at 8922d0>
由此可以看出stdin, stdout, stderr在Python中無非都是文件屬性的對象,他們在Python啟動時自動與Shell 環境中的標准輸入,輸出,出錯關聯。
而Python程序的在Shell中的I/O重定向與本文開始時舉的DOS命令的重定向完全相同,其實這種重定向是由Shell來提供的,與Python 本身並無關系。那麼我們是否可以在Python程序內部將stdin,stdout,stderr讀寫操作重定向到一個內部對象呢?答案是肯定的。
Python提供了一個StringIO模塊來完成這個設想,比如:
from StringIO import StringIO
import sys
buff =StringIO()
temp =sys.stdout #保存標准I/O流
sys.stdout =buff #將標准I/O流重定向到buff對象
print 42, 'hello', 0.001
sys.stdout=temp #恢復標准I/O流
print buff.getvalue()
閱讀全文
4. python的os.system問題 我在環境變數裡面設置了win.rar的path,(比如我的winrar在c:\winrar\)
Windows需要添加系統環境變數才能在任何路徑下訪問環境變數路徑下的程序或命令,添加環境變數後需要記得查看PATHEXT是否包含對應的程序後綴
如增加了python後,想要在任何路徑下執行py程序,需要添加Python系統path環境變數,同時增加.PY的path可執行後綴,否則無法識別.py程序及裡面的命令,如果.py程序在D盤下,就不能使用C盤的WinRAR命令,提示winrar不是內部控製程序。
5. python os.system 命令求助
看一下是不是linux系統許可權的問題。確保你對那個目錄有讀寫許可權。另外,如果是想一個指令建立多級目錄,需要用-p參數。 mkdir -p PATH
6. Python 3 中 os.system調用問題
ifnotos.path.exists(dst_dir):
os.mkdir(dst_dir)
print("thisDIR%ssetupSuccessful!"%dst_dir)
else:
print("thisDIR%sisexists!"%dst_dir)
zip_command="winrara%s%s"%(r_name,''.join(source))
#這個winrar,你在cmd能運行嗎?不能的話就加入絕對路徑
print(zip_command)
try:
os.system(zip_command)
print("傷不起!")
exceptExceptionase:
print(e)
print("命令執行失敗咯,你懂得!")
7. python中os.system函數可以執行export命令嗎
返回0是執行成功了,但是你的命令裡面的錯誤是無法收到的
比如os.system('aaa')返回0,表示執行了aaa這個命令
但是可能系統根本沒有aaa這個命令
如果你要獲得詳細的運行結果,建議使用popen命令,如下例子:
prog = subprocess.Popen("mysql -usanguo -psgtest -f <%s"%sqlFilePath, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
out,error= prog.communicate()
if prog.returncode:
print 'File import error'
return [False,error]
8. 關於在python中使用os.system運行批處理.bat文件
第一個執行後並沒有結果,因為隨著執行返回,當前目錄就改變了。
第二個可以切換當前目錄。
第三個跟第二個配合使用應該可以。或者用 os.path.join(DstDir,'test.bat') 來直接引用絕對路徑
9. python中用filedialog.askdirectory獲取文件夾路徑後用os.system函數打開失敗,因為斜杠問題。如何解決
os.system('explorer'+os.path.normpath(savefolder))
使用os.path.normpath格式化路徑
10. 如何用Python os.path.walk方法遍歷搜索文件內容的操作詳解
文中使用到了Python os模塊和Python sys模塊,這兩個模塊具體的使用方法請參考玩蛇網相關文章閱讀。
Python os.path.walk方法遍歷文件搜索內容方法代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os, sys
#代碼中需要用到的方法模塊導入
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files
def visitfile(fname, searchKey):
global fcount, vcount
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
pass
elif open(fname).read().find(searchKey) != -1:
print'%s has %s' % (fname, searchKey)
fcount += 1
except: pass
vcount += 1
#www.iplaypy.com
def visitor(args, directoryName,filesInDirectory):
for fname in filesInDirectory:
fpath = os.path.join(directoryName, fname)
if not os.path.isdir(fpath):
visitfile(fpath,args)
def searcher(startdir, searchkey):
global fcount, vcount
fcount = vcount = 0
os.path.walk(startdir, visitor, searchkey)
if __name__ == '__main__':
root=raw_input("type root directory:")
key=raw_input("type key:")
searcher(root,key)
print 'Found in %d files, visited %d' % (fcount, vcount)