gpt4 book ai didi

python - 使用 Python 程序写入和读取 cmd 提示符

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:21 24 4
gpt4 key购买 nike

为了让 Python 程序在提示符中写入类似“ls”的内容并读取(保存在 .txt 文件中)命令的输出,我需要做什么?

最佳答案

您可以使用subprocess模块调用命令:

import subprocess

# Call the command with the subprocess module
# Be sure to change the path to the path you want to list
proc = subprocess.Popen(["ls", "/your/path/here"], stdout=subprocess.PIPE)

# Read stdout from the process
result = proc.stdout.read().decode()

# Be safe and close the stdout.
proc.stdout.close()

# Write the results to a file.
with open("newfile.txt", "w") as f:
f.write(result)

但请注意..如果您只想列出一个目录,os 模块有一个 listdir() 方法:

import os

with open("newfile.txt", "w") as f:
for filename in os.listdir("/your/path/here"):
f.write(filename)

关于python - 使用 Python 程序写入和读取 cmd 提示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com