[英]Command prompt all in 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)
我想知道如何打印 output 並在運行命令時隱藏命令提示符
嘗試這個
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 系統。 這可能會為您提供一些避免屏幕上消息的上下文,但不會回答第二個問題: 隱藏控制台 output 由 os.system 生成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.