简体   繁体   English

从 python 使用命令提示符

[英]Use command prompt from python

I write a python scripts that after execute some db queries, save the result of that queries on different csv files.我编写了一个 python 脚本,在执行一些 db 查询后,将查询的结果保存在不同的 csv 文件中。

Now, it's mandatory to rename this file with the production's timestamps and so every hour i got new file with new name.现在,必须用生产的时间戳重命名这个文件,所以每小时我都会得到一个新名称的新文件。

The script run with a task scheduler every hour and after save my csv files I need to run automatically the command prompt and execute some command that includes my csv files name in the path....该脚本每小时使用任务调度程序运行一次,保存我的 csv 文件后,我需要自动运行命令提示符并执行一些在路径中包含我的 csv 文件名的命令......

Is it possible to run the cmd and paste him the path of csv file like a variable?是否可以运行 cmd 并将 csv 文件的路径像变量一样粘贴? in python I save the file in this way:在python中,我以这种方式保存文件:

date_time_str_csv1 = now.strftime("%Y%m%d_%H%M_csv1")

I don't know how to write automatically the different file name when i call the cmd当我调用 cmd 时,我不知道如何自动编写不同的文件名

If I understand your question correctly, one solution would be to simply execute the command-line command directly from the Python script.如果我正确理解您的问题,一种解决方案是直接从 Python 脚本执行命令行命令。 You can use the subprocess module from Python (as also explained here: How do I execute a program or call a system command? ).您可以使用 Python 中的 subprocess 模块(这里也有解释: 如何执行程序或调用系统命令? )。

This could look like this for example:例如,这可能如下所示:

csv_file_name = date_time_str_csv1 +".csv"
subprocess.run(["cat", csv_file_name)

You can run a system cmd from within Python using os.system:您可以使用 os.system 从 Python 中运行系统 cmd:

import os
os.system('command filename.csv')

Since the argument to os.system is a string, you can build it with your created filename above.由于os.system的参数是一个字符串,您可以使用上面创建的文件名来构建它。

you can try using the subprocess library, and get a list of the files in the folder in an array.您可以尝试使用 subprocess 库,并以数组的形式获取文件夹中的文件列表。 This example is using the linux shell:此示例使用 linux shell:

import subprocess
str = subprocess.check_output('ls', shell=True)
arr = str.decode('utf-8').split('\n')
print(arr)

After this you can iterate to find the newest file and use that one as the variable.在此之后,您可以迭代以找到最新的文件并将该文件用作变量。

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

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