【问题标题】:How to run a series of bash commands via Python?如何通过 Python 运行一系列 bash 命令?
【发布时间】:2019-04-07 19:59:02
【问题描述】:

在 Windows 系统上运行,我使用 subprocess.call() 运行 bash.exe。 以下是代码

def predict():
    os.system('notepad cmnd.txt')
    subprocess.call(['C:/Windows/System32/bash.exe'])
    print(file_contents)
    label = Label(master, text=file_contents)
    #subprocess.call(['c:/users/hp/open.py'])
    label.pack()

句柄传递给 bash,因此不执行几个命令。 在实际输入值时运行的 cd 命令返回 Missing Directory 错误。 ls 命令返回“无法运行二进制文件”错误。 我该怎么办?

【问题讨论】:

    标签: python bash operating-system


    【解决方案1】:

    我不太确定你想要什么,但如果你想在 Windows 环境中运行 bash 命令,你可以尝试使用subprocess.check_output()

    from subprocess import check_output
    
    bash_commands = ['ls', 'pwd']
    
    for command in bash_commands:
        output = check_output(['bash', '-c', command]).decode()
        print(output)
    

    在本例中,列出当前目录中的所有文件并打印出父工作目录。

    【讨论】:

    • 谢谢。我知道我有点不清楚,因为我已经为此工作了一段时间,并且已经忘记了自己的位置和内容。 :( 让我试一试,
    • @AbhinavSrivastav 没问题。这个例子对于你想做的事情来说可能过于简单了,但它应该给出一个大致的想法。
    猜你喜欢
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2021-03-20
    • 2019-02-22
    • 2014-04-07
    • 2012-10-23
    相关资源
    最近更新 更多