我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
我会建议使用子过程模块而不是os.system,因为它会让您逃脱,因此更安全。
subprocess.call(['ping', 'localhost'])
其他回答
如果您需要从 Python 笔记本电脑(如 Jupyter、Zeppelin、Databricks 或 Google Cloud Datalab)中拨打一个支票命令,您只能使用! 预定。
例如,
!ls -ilF
在Linux中,如果您想打电话给一个将独立执行的外部命令(在Python脚本结束后将继续运行),您可以使用一个简单的字符串作为任务插槽或命令中的命令。
例如,Task Spooler:
import os
os.system('ts <your-command>')
關於Task Spooler(TS)的評論:
您可以设置要运行的竞争对手过程的数量(“插槽”)与: ts -S <插槽的号码> 安装 ts 不需要管理特权. 您可以从源头下载并编写一个简单的创建,将其添加到您的路径,并完成。
有很多不同的图书馆,允许您使用Python呼叫外部命令. 对于每个图书馆,我给了一个描述,并显示了一个例子呼叫外部命令. 我使用的命令作为例子是ls -l(列出所有文件)。 如果你想了解更多关于任何图书馆,我列出并链接到文件的每一个。
来源
这些都是图书馆
希望这会帮助你做出决定哪个图书馆使用:)
副过程
subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command
os 用于“操作系统依赖功能”。 它也可以用来呼叫与 os.system 和 os.popen 的外部命令(注:也有 subprocess.popen)。 os 总是会运行盾牌,并且对于那些不需要或不知道如何使用 subprocess.run 的人来说是一个简单的替代方案。
os.system("ls -l") # Run command
os.popen("ls -l").read() # This will run the command and return any output
饰 sh
sh 是一个子过程界面,允许您呼叫程序,就好像它们是功能。
sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function
铅
ls_cmd = plumbum.local("ls -l") # Get command
ls_cmd() # Run command
佩克斯
pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo user@example.com:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')
织物
fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output
发送
r = envoy.run("ls -l") # Run command
r.std_out # Get output
命令
我会推荐下面的“运行”方法,它会帮助我们获得标准输出、标准错误和输出状态作为词典;这个词典的呼叫者可以通过“运行”方法阅读词典返回,以了解过程的实际状态。
def run (cmd):
print "+ DEBUG exec({0})".format(cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
(out, err) = p.communicate()
ret = p.wait()
out = filter(None, out.split('\n'))
err = filter(None, err.split('\n'))
ret = True if ret == 0 else False
return dict({'output': out, 'error': err, 'status': ret})
#end
Python 3.5 以上
import subprocess
p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())
网上尝试
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从终端/命令行调用VS代码编辑器
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出