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

问题描述 投票:-2回答:2

为了使Python程序在提示符中写入“ls”并读取(保存在.txt文件中)命令的输出,我该怎么做?

python linux python-3.x prompt
2个回答
1
投票

您可以使用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)

0
投票

Python可用于执行bash和批处理命令(Linux和Windows),方法是:

subprocess.check_call([“ls”,“ - l”])

© www.soinside.com 2019 - 2024. All rights reserved.