Home > Net >  Use command prompt from python
Use command prompt from python

Time:04-27

I got this problem.

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

My question is: It's 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

Thanks!!

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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.

  • Related