Python script command line input - python

To start i have little knowledge of python as i'm doing this assignment as a school project. I need to achieve the folowing:
create a script which i can start from Windows CMD and i need to add a parameter list to the first 3 files in a directory.
i start the script as follows:
c:\Python34\python.exe c:\Python34\directory.py c:\temp 3
content of the script:
##directory.py###
import os
import sys
dirs = os.listdir(sys.argv[1])
print (dirs)
The problem is i dont think the command line switch "3" is input in the script.
Any idea how i can achive this?

Your code doesn't actually reference the second command-line variable.
Are you trying to list the first n files in a directory? If so then try
import os
import sys
dir_arg=sys.argv[1]
num_arg=int(sys.argv[2]) #need to convert second argument to a number
dirs=os.listdir(dir_arg)
print dirs[:num_arg]

As other's have said sys.argv is simply a collection of command line arguments, so all you have to do is change your index in order to grab the appropriate values.

Related

Can i have some python code in second file and when i run the first file its like the code is inside the first file?

I have 2 python files and i want to run the second file in the first one like the code in the second file was inside the first file. Is this possible and if so how?
I dont know what to try please help. Thanks!
Just like how you can use import to import other python libraries (built-in or third-party), you can also import your own libraries/modules/files. if the two files are in the same directory, you can do import file2 at the top of file one and run any of the functions or modules within it.
ex:
# this is file_2
def main():
print('this is from file_2')
# this is file_1
import file_2
file_2.main()
If you then run file_1 (you could run python file_1.py from the terminal, or however you run it), it will print out 'this is from file_2'

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.

Sikuli get part of a filepath - Split string

I want to get a number from the filepath of the current file in Sikuli - Jython
I have a python example of what i'm trying to achive.
In the example the path is:
C:\PycharmProjects\TestingPython\TestScripts\TestScript_3.sikuli\TestScript.py
import os
PointerLeft = "Script_"
PointerRight = ".sikuli"
FilePath = os.path.dirname(os.path.abspath(__file__))
NumberIWant = FilePath[FilePath.index(PointerLeft) + len(PointerLeft):FilePath.index(PointerRight)]
print(NumberIWant)
So what i want to get is the number 3. In python the example above works, but I cant use the __file__ ref in Sikulix. Nor does the split of the string work, so even if I get the string of the path, I still have to get the number.
Any help and/or ideas is greatly appreciated
Important:
the .py file in a .sikuli folder must have the same name
hence in your case: ...\TestScript_3.sikuli\TestScript_3.py
It looks like you are trying to run your stuff in the PyCharmcontext. If you do not run the script in the SikuliX IDE, you have to add from sikuli import * even to the main script.
To get the file path of the script use getBundlePath().
Then os.path(getBundlePath()).basename() will result to the string "TestScript_3.sikuli".
RaiMan from SikuliX

Call all files from a menu

I've got a task to do that is crushing my head. I have five .py documents and I want to make a menu in another .py so I can run any of them by introducing a string inside an input() but don't really see the way to do that and I don't know if there is somehow I can.
I have tried import every file to the 6th file but I don't even know how to start.
I would like it just to be seen as simple as it can sound, but yet I find it really hard.
If you just want to run them, then try this:-
import os
file_path = input("Enter the path of your file = ")
os.system(file_path)
If the file that you are trying to execute is not in the current
directory, i.e. doesn't exist in the same folder as the currently
executing python file, then you have to provide it's full path.
Path Format:-. C:\Users\lmYoona\OneDrive\Desktop\example.py
If the python file you are trying to execute is in the same directory as
the currently executing python file, then abstract name will also
work
Path Format:- example.py
P.S.:- I would only recommend this method if all you want is just to execute the other python file, rather then importing stuff from it.

How to open any program in Python?

Well I searched a lot and found different ways to open program in python,
For example:-
import os
os.startfile(path) # I have to give a whole path that is not possible to give a full path for every program/software in my case.
The second one that I'm currently using
import os
os.system(fileName+'.exe')
In second example problem is:-
If I want to open calculator so its .exe file name is calc.exe and this happen for any other programs too (And i dont know about all the .exe file names of every program).
And assume If I wrote every program name hard coded so, what if user installed any new program. (my program wont able to open that program?)
If there is no other way to open programs in python so Is that possible to get the list of all install program in user's computer.
and there .exe file names (like:- calculator is calc.exe you got the point).
If you want to take a look at code
Note: I want generic solution.
There's always:
from subprocess import call
call(["calc.exe"])
This should allow you to use a dict or list or set to hold your program names and call them at will. This is covered also in this answer by David Cournapeau and chobok.
You can try with os.walk :
import os
exe_list=[]
for root, dirs, files in os.walk("."):
#print (dirs)
for j in dirs:
for i in files:
if i.endswith('.exe'):
#p=os.getcwd()+'/'+j+'/'+i
p=root+'/'+j+'/'+i
#print(p)
exe_list.append(p)
for i in exe_list :
print('index : {} file :{}'.format(exe_list.index(i),i.split('/')[-1]))
ip=int(input('Enter index of file :'))
print('executing {}...'.format(exe_list[ip]))
os.system(exe_list[ip])
os.getcwd()+'/'+i prepends the path of file to the exe file starting from root.
exe_list.index(i),i.split('/')[-1] fetches just the filename.exe
exe_list stores the whole path of an exe file at each index
Can be done with winapps
First install winapps by typing:
pip install winapps
After that use the library:
# This will give you list of installed applications along with some information
import winapps
for app in winapps.list_installed():
print(app)
If you want to search for an app you can simple do:
application = 'chrome'
for app in winapps.search_installed(application):
print(app)

Categories

Resources