代码中执行命令行-Python与Java版
2015-10-16 16:45
591 查看
这里的命令是指在开始-->运行里输的命令,如:ping www.baidu.com
要运行dos命令,如dir,直接在开始-->运行里执行会报错,此时需要调用cmd来执行dir,完整命令为:cmd /k dir
参数说明:
这是CMD下输出path环境变量的命令,以下代码都可以在Sublime Text控制台中输出结果:
Python代码:
或者:
import os
s = os.system("echo %path%")
Java代码(略去try catch):
Python代码:
Java代码(略去try catch):
要运行dos命令,如dir,直接在开始-->运行里执行会报错,此时需要调用cmd来执行dir,完整命令为:cmd /k dir
参数说明:
/k 表示执行完命令后不关闭cmd窗口 /c 表示执行完命令后关闭cmd窗口 /k或/c后还可以加一个start,表示在新的cmd窗口中执行后面的命令
一、不需要后续输入
以如下命令为例:echo %path%
这是CMD下输出path环境变量的命令,以下代码都可以在Sublime Text控制台中输出结果:
Python代码:
import subprocess r = subprocess.call(['cmd', '/k', 'echo', '%path%'])
或者:
import os
s = os.system("echo %path%")
Java代码(略去try catch):
Process p = Runtime.getRuntime().exec("cmd /k echo %path%"); // 数据从进程流向本程序,从本程序的角度,是输入流 BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String buff = null; while((buff = br.readLine()) != null){ System.out.println(buff); } br.close();
二、需要后续输入
以如下命令为例:adb shell adb help exit第一行是进入adb shell,第二行是输出帮助信息,第三行是退出shell。这些命令需要你的电脑已经安装Android adb工具,同时连上手机或者启动了Android 虚拟机。
Python代码:
import subprocess p = subprocess.Popen(['adb', 'shell'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = p.communicate(b'adb help\nexit\n') print(output.decode('utf-8'))
Java代码(略去try catch):
Process process = Runtime.getRuntime().exec("adb shell"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.write("adb help\nexit\n".getBytes()); os.flush(); int result = process.waitFor(); StringBuilder successMsg = new StringBuilder(); StringBuilder errorMsg = new StringBuilder(); BufferedReader successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); String s; while ((s = successResult.readLine()) != null) { successMsg.append(s); } while ((s = errorResult.readLine()) != null) { errorMsg.append(s); } os.close(); successResult.close(); errorResult.close(); process.destroy();
相关文章推荐
- Python编程中的文件操作攻略
- makefile太难了,学不会,自己用Python写个简单的构建工具
- <LeetCode><Easy> 160 Intersection Of Two Listed Lists
- leetcode之Two Sum
- python-转换成exe文件(py2exe)
- 详解Python编程中包的概念与管理
- python两个 list 获取交集,并集,差集的方法
- python3.x的print()函数默认参数
- python中os.walk()遍历目录中所有文件
- 解读Python编程中的命名空间与作用域
- Python中的模块导入和读取键盘输入的方法
- <LeetCode><Easy> 165 CompareVersionNumbers
- python中文件OS模块访问函数
- 统计文件字数,并按出现次数打印结果
- R软件中jiebaR包分词和用python中jieba分词以及做关键字提取及LDA模型
- <LeetCode><Easy> 168 Excel Sheet Column Title
- 第四章 python中的面向对象设计
- Python-爬虫初学
- [LeetCode]题解(python):027-Remove Element
- python核心编程 练习题7.5