开发者

What is the Python equivalent of Perl's backticks? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Equivalent of Backticks in Python

When I want to write directly to the command prompt in Perl, I can do something like this:

Perl File test.pl:

$directory = `dir`;  
print $directory;

Which would output something like..

C:\Documents and Settings\joslim\Desktop>perl test.pl

Volume in drive C has no开发者_开发问答 label. Volume Serial Number is EC37-EB31

Directory of C:\Documents and Settings\joslim\Desktop

(and a listing of all the files..)

Can I do this in Python? I've searched around but have had no luck.

Also, can you tell me what this is called? I'm sure there's a more technical term than "writing directly to the command prompt"...


What you are referring to in Perl is the backtick operator, which also behaves identically in PHP.

What you are looking to achieve is to execute a command line operation.

The equivalent in Python of the backtick operator, and how to run a command line program and retrieve the output, has been answered in: Equivalent of Backticks in Python


The equivalent is commands.getoutput. So for your example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜