python中有没有一种方法可以判断变量是否是系统命令

2024-05-13 08:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python制作一个shell仿真器,但是我想将用户输入保存到一个名为x的变量中,如果它是一个系统命令

我试着把他们的每一个命令都列出来,但是那太费时了

import os
while True:
  execute = input(">")
  os.system(execute)

Tags: 用户import命令trueinputexecuteosshell
1条回答
网友
1楼 · 发布于 2024-05-13 08:45:41

如果已经有命令列表,可以执行以下操作:

>>> from subprocess import Popen, PIPE
>>> 
>>> 
>>> def get_stderr(cmd):
...     return Popen(cmd, shell=True, stderr=PIPE).communicate()[1]
... 
>>> 
>>> for c in ['garbage_cmd1', 'grep', 'which', 'garbage_cmd2']:
...     if 'not found' in get_stderr(c).decode():
...         print('%s is not valid' % c)
...     else:
...         print('%s is valid' % c)
... 
garbage_cmd1 is not valid
grep is valid
which is valid
garbage_cmd2 is not valid

如果您在Linux机器上,也可以运行compgen -c >> cmds.txt

相关问题 更多 >