【问题标题】:What is the Python equivalent of Perl's backticks? [duplicate]Perl 的反引号的 Python 等价物是什么? [复制]
【发布时间】:2011-04-25 14:50:16
【问题描述】:

可能重复:
Equivalent of Backticks in Python

当我想在 Perl 中直接写入命令提示符时,我可以这样做:

Perl 文件 test.pl

$directory = `dir`;  
print $directory;

这会输出类似..

C:\文档和 Settings\joslim\Desktop>perl test.pl

驱动器 C 中的卷没有标签。 卷序列号为 EC37-EB31

C:\Documents 目录和 设置\joslim\桌面
(以及所有文件的列表..)

我可以在 Python 中做到这一点吗?我四处寻找,但没有运气。

另外,你能告诉我这叫什么吗?我敢肯定有一个比“直接写入命令提示符”更专业的术语......

【问题讨论】:

标签: python perl terminal cmd


【解决方案1】:

您在 Perl 中指的是反引号运算符,它在 PHP 中的行为也相同。

您要实现的是执行命令行操作。

反引号运算符在 Python 中的等价物,以及如何运行命令行程序并检索输出,已在:Equivalent of Backticks in Python

中得到解答

【讨论】:

    【解决方案2】:

    相当于commands.getoutput。所以对于你的例子:

    import commands
    directory = commands.getoutput("dir")
    print directory
    

    【讨论】:

    • 啊,谢谢。我看到它已被弃用,我现在要使用 subprocess 模块。
    猜你喜欢
    • 2011-02-02
    • 2012-03-20
    • 1970-01-01
    • 2016-02-08
    • 2010-11-27
    • 2021-07-01
    • 1970-01-01
    • 2010-09-27
    • 2022-11-11
    相关资源
    最近更新 更多