我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
最多案例:
在大多数情况下,一个短片的代码,如此,是你将需要的一切:
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)
其他回答
我为此写了一本图书馆,shell.py。
它基本上是现在的旋转器和旋转器,它还支持旋转命令,所以你可以在Python中更容易进行连锁命令,所以你可以做这样的事情:
ex('echo hello shell.py') | "awk '{print $2}'"
使用:
import os
cmd = 'ls -al'
os.system(cmd)
os - 此模块提供一个可携带的方式来使用操作系统依赖的功能。
对于更多的 OS 功能,这里是文档。
步骤1:添加模块
import subprocess
subprocess.run(["ls", "-l"])
步骤2:呼叫外部命令
import subprocess
result = subprocess.run(["ls"], capture_output=True)
print(result.stdout)
提示: shlex.split() 方法可以用来将简单的 shell 命令分解到单个论点,但它可能不会正确地与包含管道符号的更长和更复杂的命令一起工作,这可能会使漏洞变得困难。
安全影响:在运行外部命令时,您应该小心正确逃避包含特殊字符的任何论点,因为它们可能会被阴影以意想不到的方式解释。
子过程模块提供了更强大的设施,以便扫描新过程并获取其结果;使用该模块,最好使用此功能。 请参见子过程模块部分的替代老功能,在子过程文档中找到一些有用的食谱。
注意: 在 Python 3.4 或更高版本中,使用 subprocess.call 而不是.run:
subprocess.call(["ls", "-l"])
如果您使用 Python 3.5 +,请使用 subprocess.run()。
在Python中呼叫外部命令
一个简单的方式来呼叫一个外部命令是使用os.system(...). 这个功能返回命令的输出值. 但缺点是我们不会得到 stdout 和 stderr。
ret = os.system('some_cmd.sh')
if ret != 0 :
print 'some_cmd.sh execution returned failure'
在背景下在Python中呼叫外部命令
subprocess.Popen 提供更多的灵活性运行一个外部命令而不是使用 os.system. 我们可以在背景下启动一个命令,等待它完成。
proc = subprocess.Popen(["./some_cmd.sh"], stdout=subprocess.PIPE)
print 'waiting for ' + str(proc.pid)
proc.wait()
print 'some_cmd.sh execution finished'
(out, err) = proc.communicate()
print 'some_cmd.sh output : ' + out
在背景下在Python中呼叫一个长期运行的外部命令,并在一段时间后停止
我们甚至可以在背景下开始一个漫长的运行过程,使用subprocess.Popen,并在任务完成后一次杀死它。
proc = subprocess.Popen(["./some_long_run_cmd.sh"], stdout=subprocess.PIPE)
# Do something else
# Now some_long_run_cmd.sh exeuction is no longer needed, so kill it
os.system('kill -15 ' + str(proc.pid))
print 'Output : ' proc.communicate()[0]
有很多不同的图书馆,允许您使用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
命令
推荐文章
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节