>>> import os
>>> os.system("echo \"Hello World\"") # 直接使用os.system调用一个echo命令
Hello World ——————> 打印命令结果
0 ——————> What's this ? 返回值?
>>> val = os.system("ls -al | grep \"log\" ") # 使用val接收返回值
-rw-r--r-- 1 root root 6030829 Dec 31 15:14 log ——————> 此时只打印了命令结果
>>> print val
0 ——————> 注意,此时命令正常运行时,返回值是0
>>> val = os.system("ls -al | grep \"log1\" ")
>>> print val
256 ——————> 使用os.system调用一个没有返回结果的命令,返回值为256~
>>>
>>> os.popen('ls -lt') # 调用os.popen(cmd)并不能得到我们想要的结果
<open file 'ls -lt ', mode 'r' at 0xb7585ee8>
>>> print os.popen('ls -lt').read() # 调用read()方法可以得到命令的结果
total 6064
-rwxr-xr-x 1 long long 23 Jan 5 21:00 hello.sh
-rw-r--r-- 1 long long 147 Jan 5 20:26 Makefile
drwxr-xr-x 3 long long 4096 Jan 2 19:37 test
-rw-r--r-- 1 root root 6030829 Dec 31 15:14 log
drwxr-xr-x 2 long long 4096 Dec 28 09:36 pip_build_long
drwx------ 2 Debian-gdm Debian-gdm 4096 Dec 23 19:08 pulse-gylJ5EL24GU9
drwx------ 2 long long 4096 Jan 1 1970 orbit-long
>>> val = os.popen('ls -lt').read() # 使用变量可以接收命令返回值
>>> if "log" in val: # 我们可以使用in来判断返回值中有木有一个字符串
... print "Haha,there is the log"
... else:
... print "No,not happy"
...
Haha,there is the log
long@zhouyl:/tmp/tests$ python
Python 2.7.3 (default, Jan 2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import commands
>>> commands.getstatusoutput('ls -lt') # 返回(status, output)
(0, 'total 5900\n-rwxr-xr-x 1 long long 23 Jan 5 21:34 hello.sh\n-rw-r--r-- 1 long long 147 Jan 5 21:34 Makefile\n-rw-r--r-- 1 long long 6030829 Jan 5 21:34 log')
>>> commands.getoutput('ls -lt') # 返回命令的输出结果(貌似和Shell命令的输出格式不同哈~)
'total 5900\n-rwxr-xr-x 1 long long 23 Jan 5 21:34 hello.sh\n-rw-r--r-- 1 long long 147 Jan 5 21:34 Makefile\n-rw-r--r-- 1 long long 6030829 Jan 5 21:34 log'
>>> commands.getstatus('log') # 调用commands.getoutput中的命令对'log'文件进行相同的操作
'-rw-r--r-- 1 long long 6030829 Jan 5 21:34 log'
>>>
return_code = subprocess.call("echo Hello World", shell=True)
awk 'NR==m,NR==n {print $k}' path/filename
awk 'NR==m {print $k}' path/filename
import linecache theline = linecache.getline(filepath, line_number)
# cat a.txt
1a 2b 3c 4d 5e 6f 7g
>>> a=linecache.getlines('a.txt')
>>> a
['1a\n', '2b\n', '3c\n', '4d\n', '5e\n', '6f\n', '7g\n']
>>> a=linecache.getlines('a.txt')[0:4]
>>> a
['1a\n', '2b\n', '3c\n', '4d\n']
>>> a=linecache.getline('a.txt',4)
>>> a
'4d\n'
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有