简体   繁体   中英

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.

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....

Is it possible to run the cmd and paste him the path of csv file like a variable? in python I save the file in this way:

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

If I understand your question correctly, one solution would be to simply execute the command-line command directly from the Python script. You can use the subprocess module from Python (as also explained here: How do I execute a program or call a system command? ).

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:

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.

you can try using the subprocess library, and get a list of the files in the folder in an array. This example is using the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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