【问题标题】:Python code to send command through command line通过命令行发送命令的 Python 代码
【发布时间】:2012-04-05 12:04:23
【问题描述】:
final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\""  + "  /p " + str
os.system(final)

我正在尝试使用 Python 设置文件夹的权限,但是在运行此命令时,也需要提供用户输入,即

它询问您是否确定(Y/N),用户需要输入“Y”或“N”

有什么方法可以使用 python 将用户输入“Y”连同上述代码一起发送?

    pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE)
    pro.communicate(bytes("Y\r\n",'utf-8'))

我添加了以下代码。程序不设置权限就退出。

http://jimmyg.org/blog/2009/working-with-python-subprocess.html#writing-to-standard-input

【问题讨论】:

  • 除了你的问题:这不是 PHP 或 Javascript - Python hamore 可读的连接字符串的方式,而且它们要好得多。例如,尝试:`final = "cacls %s\"%s %s\" /p %s" % ("E:/", list1[2], list1[3], str)

标签: python windows os.system


【解决方案1】:

尝试使用子进程模块

import subprocess
cmd = ["cacls",  "E:/" + list1[2], list1[3], "/p", str]

pro = subprocess.Popen(final, stdin=subprocess.PIPE)
pro.communicate("y\r\n")

【讨论】:

  • 嗨,jakob,我试过你的解决方案,程序永远不会退出并且权限没有设置
  • 同样的输出,这次我可以看到正在执行的 cacls.exe。程序不退出。
  • 1.使用列表而不是字符串来传递参数;这使您可以摆脱所有最终会中断的愚蠢引用。 2.尝试"y\r\n"而不是"y"
  • 这也可能是一个使用 str.format 的建议,这样构建这些字符串会变得更漂亮吗?
  • 嗨亚伦,还是同样的问题。
【解决方案2】:

作为聪明的程序员,请使用PBS

那么,代码是:

from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one

script = Command("/path/to/cacls ")
print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\""  + "  /p " + str).split())

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多