命令提示符全部用python编写



我基本上是在尝试用python运行命令提示符应该很简单这里有这段代码

import os
fileplace = 'C/:'
a = input(fileplace)
b = os.system('cmd /c '+a)
if b == 1:
print('error with command')
else:
print('ran '+a)

,我想知道当我运行命令

时,如何打印输出并隐藏命令提示符

试试这个

import os

cmd = input('C/:')
stream = os.popen(f'cmd /c {cmd}')
output = stream.read()
if output == '':
print(f'Error with {cmd}')
else:
print(f'ran {cmd}')

您的代码有几个问题。首先,成功os.system的默认错误是0。错误代码可以非常依赖于发生的事情,因此用b == 1标识它是不够的。例如,如果您使用了不正确的命令(即,未找到命令),它将在Unix上给您32512。

所以这是我对代码的建议修订,并对更改进行了一些注释:

import os
fileplace = 'C:'.  # Note that I changed this for correct path (in case you use it)
a = input(fileplace)  # I get that you're trying to get a path but you're not passing the full path
b = os.system('cmd /c '+a)  #Not sure what /c is intended for here
if b == 0: # This will pass on successful execution
print('ran '+a)
else:  # This will not pass 
print('error with cmd')

至于隐藏消息,您可以将其传递给dev/null。然而,因为你在Windows上,我不完全确定这将如何工作,因为我发现的解决方案是Linux/UNIX系统。这可能会给您提供一些上下文来避免屏幕上的消息,但不会回答第二个问题:隐藏os.system

产生的控制台输出

相关内容

最新更新