我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
作为一个例子(在Linux):
import subprocess
subprocess.run('mkdir test.dir', shell=True)
这在当前目录中创建 test.dir. 请注意,这也是有效的:
import subprocess
subprocess.call('mkdir test.dir', shell=True)
使用 os.system 的同等代码是:
import os
os.system('mkdir test.dir')
最好的做法是使用子过程而不是OS,与.run 受欢迎的.call. 所有你需要知道的子过程在这里. 此外,请注意,所有的 Python 文档都可以从这里下载. 我下载了 PDF 包装为.zip. 我提到这一点,因为有一个好概述的OS 模块在 tutorial.pdf (页面 81 ) 。 此外,它是一个授权的资源的 Python 编码器。
其他回答
如果您正在写一个 Python shell 脚本,并且在您的系统上安装了 IPython,您可以使用 bang 预定来在 IPython 中运行一个 shell 命令:
!ls
filelist = !ls
可以是这样简单的:
import os
cmd = "your command"
os.system(cmd)
Python 3.5 以上
import subprocess
p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())
网上尝试
您可以尝试使用 os.system() 运行外部命令。
例子:
import os
try:
os.system('ls')
pass
except:
print("Error running command")
pass
在示例中,脚本输入OS并试图运行在OS.system()中列出的命令。如果命令失败,那么它将打印“错误运行命令”而没有脚本因错误而停止。
是的,只是如此简单!
最多案例:
在大多数情况下,一个短片的代码,如此,是你将需要的一切:
import subprocess
import shlex
source = "test.txt"
destination = "test_copy.txt"
base = "cp {source} {destination}'"
cmd = base.format(source=source, destination=destination)
subprocess.check_call(shlex.split(cmd))
它是干净和简单的。
subprocess.check_call 以论点运行命令,等待命令完成。 shlex.split 使用 shell-like syntax 分割行 cmd
其他案例:
如果这不适用于某些特定的命令,最有可能你有一个问题与命令线的解释器. 操作系统选择了默认一个不适合你的程序类型或可能没有找到适当的一个在系统可执行的路径。
例子:
使用Unix系统上的转向操作器
input_1 = "input_1.txt"
input_2 = "input_2.txt"
output = "merged.txt"
base_command = "/bin/bash -c 'cat {input} >> {output}'"
base_command.format(input_1, output=output)
subprocess.check_call(shlex.split(base_command))
base_command.format(input_2, output=output)
subprocess.check_call(shlex.split(base_command))
正如《Python Zen: Explicit is better than implicit》中所说的那样。
因此,如果使用 Python >=3.6 函数,它会看起来像这样:
import subprocess
import shlex
def run_command(cmd_interpreter: str, command: str) -> None:
base_command = f"{cmd_interpreter} -c '{command}'"
subprocess.check_call(shlex.split(base_command)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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命令的全部输出