我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
经过一些研究,我有下面的代码,这对我来说非常好,它基本上在实时打印了标准输出和标准错误。
stdout_result = 1
stderr_result = 1
def stdout_thread(pipe):
global stdout_result
while True:
out = pipe.stdout.read(1)
stdout_result = pipe.poll()
if out == '' and stdout_result is not None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
def stderr_thread(pipe):
global stderr_result
while True:
err = pipe.stderr.read(1)
stderr_result = pipe.poll()
if err == '' and stderr_result is not None:
break
if err != '':
sys.stdout.write(err)
sys.stdout.flush()
def exec_command(command, cwd=None):
if cwd is not None:
print '[' + ' '.join(command) + '] in ' + cwd
else:
print '[' + ' '.join(command) + ']'
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
)
out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))
err_thread.start()
out_thread.start()
out_thread.join()
err_thread.join()
return stdout_result + stderr_result
其他回答
我会建议使用子过程模块而不是os.system,因为它会让您逃脱,因此更安全。
subprocess.call(['ping', 'localhost'])
最多案例:
在大多数情况下,一个短片的代码,如此,是你将需要的一切:
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)
>>> from subprocess import run
>>> from shlex import split
>>> completed_process = run(split('python --version'))
Python 3.8.8
>>> completed_process
CompletedProcess(args=['python', '--version'], returncode=0)
下面是最简单的使用的例子 - 它正如所要求的那样:
>>> from subprocess import run
>>> from shlex import split
>>> completed_process = run(split('python --version'))
Python 3.8.8
>>> completed_process
CompletedProcess(args=['python', '--version'], returncode=0)
>>> completed_process.args
['python', '--version']
>>> completed_process.returncode
0
如果您想捕获输出,您可以将 subprocess.PIPE 转移到适当的 stderr 或 stdout:
>>> from subprocess import PIPE
>>> completed_process = run(shlex.split('python --version'), stdout=PIPE, stderr=PIPE)
>>> completed_process.stdout
b'Python 3.8.8\n'
>>> completed_process.stderr
b''
相应的属性返回比特。
>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.\n This is indented.\n'
下面是源头的真实签名,如助(run)所示:
输入可以是一个字符串(或单码,如果指定编码或 universal_newlines=True)将被带到子过程的stdin。
这个 check=true 的例子比我可以看到的更好:
波恩
def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=None,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=(), *, user=None, group=None, extra_groups=None,
encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
了解Popen的剩余文档将作为读者的练习留下来。
有很多方法可以命令。
例如:
如果 and.exe 需要 2 个参数. 在 cmd 我们可以呼叫 sample.exe 使用此: and.exe 2 3 并在屏幕上显示 5。
如果我们使用 Python 脚本来呼叫 and.exe,我们应该这样做。
os.system(cmd,...) os.system(("and.exe" + "" + "2" + " + "3") os.popen(cmd,...) os.popen(("and.exe" + " + "2" + " + "3")) subprocess.Popen(cmd,...) subprocess.Popen(("and.exe" + " + "2" + " + "3"))
它太硬了,所以我们可以与一个空间加入CMD:
import os
cmd = " ".join(exename,parameters)
os.popen(cmd)
苏丹是一个最近为此而设计的包,它提供了管理用户特权和添加有用的错误消息的一些好处。
from sultan.api import Sultan
with Sultan.load(sudo=True, hostname="myserver.com") as sultan:
sultan.yum("install -y tree").run()
推荐文章
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节