开发者

python variable in the function call

i'm trying to create a directory/folder in开发者_开发技巧 linux using python. I will get date time and make a folder.

In [65]: d = datetime.datetime.now()

In [66]: a = 'date :' + str(d)

In [67]: a
Out[67]: 'date :2011-02-01 13:05:58.642704'

In [68]: os.system('mkdir a')

How should i pass the variable a in the system command??


Use string formatting to add the var a to the string:

os.system('mkdir %s' % a)


Use python's own way of making directories:

os.mkdir(a)


Are you sure you want to name your directory 'date :2011-02-01 13:05:58.642704' with all those colons and spaces? There is a simple way to format the date in a different form, that will make the string manipulation easier.

For example:

d = datetime.datetime.now()

a = d.strftime('date_%Y%m%d_%H%M%S_%f')
os.mkdir(a)

which will create a directory named date_20110201_130558_642704 (more about the formatting options here). Your life will be easier if you manipulate this directory in the shell (double-clicking on its name in an ls output, etc.)


You should not use os.system. Use subprocess if you have to call an external program.

That said, there is no reason to call mkdir. Use the stdlib function os.mkdir, that does what you want. Using the stdlib wherever possible is recommended. Not only will your code be portable, it will be easier to maintain and read also.

If you insist on calling an external process:

>>> import subprocess
>>> subprocess.call(['mkdir', 'foo_bar'])  
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜