简体   繁体   English

函数调用中的python变量

[英]python variable in the function call

i'm trying to create a directory/folder in linux using python. 我正在尝试使用python在linux中创建目录/文件夹。 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?? 我应该如何在系统命令中传递变量a?

使用字符串格式将var a添加到字符串:

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

使用python自己的目录制作方式:

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? 您确定要将所有冒号和空格都命名为目录'date :2011-02-01 13:05:58.642704'吗? 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 ). 它将创建一个名为date_20110201_130558_642704的目录(有关此处的格式化选项的更多信息)。 Your life will be easier if you manipulate this directory in the shell (double-clicking on its name in an ls output, etc.) 如果您在外壳中操作此目录(在ls输出中双击其名称,等等),将会使您的生活更加轻松。

You should not use os.system . 应该使用os.system Use subprocess if you have to call an external program. 如果必须调用外部程序,请使用子进程

That said, there is no reason to call mkdir . 就是说,没有理由调用mkdir Use the stdlib function os.mkdir , that does what you want. 使用stdlib函数os.mkdir即可完成所需的工作 Using the stdlib wherever possible is recommended. 建议尽可能使用stdlib。 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'])  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM