CMD command from C (visual studio) - python

So I want to execute a python file which is in my program files folder using visual studio C project.(FYI using the exe file).
I know system function can execute a command. I want to say to my command that go to the python folder in appdata and then run that a python file which is in my program file folder.
I tried the following way
char cmd[] = "C:\Users\%user%\AppData\Local\Programs\Python\Python37" "C:\Program Files (x86)\tool\tool.py";
system(cmd);
But it's giving me an error filename,directory name incorrect. Also it's an application so it should be user specific. how to i replace %user% with the actual username.
The second approach I tried is to set the python as environment variable. and then run
char cmd[] = "python " "C:\Program Files (x86)\tool\tool.py";
Since there is a space between program and files. the error says cannot find C:\Program. how do i say the compiler to include space as a part of the directory?

Let's talk.
First I don't think that
char cmd[] = "C:\Users\%user%\AppData\Local\Programs\Python\Python37" "C:\Program Files (x86)\tool\tool.py";
does what you think it does. When you put two strings like that together the compiler treats it as one long string and you will not get a space between the "...Python37" and "C:...". Better to just make that one string and put your space delimiter in.
For example:
char cmd[] = "C:\Users\%user%\AppData\Local\Programs\Python\Python37 C:\Program Files (x86)\tool\tool.py";
The next issue is that C strings reserve the '\' (back-slash) character as an "escape" character. There's a history lesson in that terminology but that's for another day. The important part is that it allows you to put characters into strings that you would not normally be able to. Examples are things like tabs (\t), newlines (\n), etc. Whenever the compilers sees a "\" it will be expecting another character to complete the "escape sequence". If you actually want a backslash you have to put in two.
For example:
char cmd[] = "C:\\Users\\%user%\\AppData\\Local\\Programs\\Python\\Python37 C:\\Program Files (x86)\\tool\\tool.py";
Next, you are using an environment variable expansion "%user%". I assume that is defined in your environment (it isn't in mine). You need to be mindful of the environment and you may want to check that things are expanding as you expect. One easy way to do this is using your same code but a different cmd string:
For example:
char cmd[] = "echo %USER% >c:\\mydir\\myoutput";
system(cmd);
It's useful to put a full path on the redirect to make sure it ends up where you expect it to. Again I'm going to assume that %USER% is correctly defined in your environment.
Next, you are referencing a file path that has a space in it. That might be why you tried to use the quotes the way you did, but in this case that doesn't help you. The system function accepts a string and for the most part doesn't much care what it is. You need something to indicate that the space is part of the file path. This is where those back-slashes can really help you.
For example:
char cmd[] = "C:\\Windows\\system32\\cmd.exe /K dir \"C:\\Program Files (x86)\"";
system(cmd);
That should open a DOS/CMD window on your desktop, execute a dir of "C:\Program Files (x86)" then leave the cmd shell open. Sometimes leaving the shell open in this way can be handy to see what the default env is.
So putting it altogether your program should look something like this:
int main() {
char cmd[] = "C:\\Users\\%user%\\AppData\\Local\\Programs\\Python\\Python37 \"C:\\Program Files (x86)\\tool\\tool.py\"";
system(cmd);
}

Related

Python(on Win10): Path issue replacing "\" with "/"

Preface: I am a beginner to Python
Problem statement: I am writing a script wherein I will be launching an application (Gotit.exe) sitting at particular path lets say D:\Some Folder\SomeMore Folder\AgainFolder\myPythonFolder\Gotit.exe. I have kept the python-script also in myPythonFolder.
I am accessing the folder path via os.path.dirname(os.path.realpath(__file__)) and selecting particular application by appending it with \Gotit.exe but when passing the same appended string stored in a variable i.e. GotitexePath to os.system(GotitexePath) its throwing error as,
'D:\Some ' is not recognized as an internal or external command,
operable program or batch file.**
Kindly help me out to solve the said issue
I am using python 3.8.2 on Win10 Machine
The error is pointing to Some Folder name. Since there is a space in path you provide, the system doesn't know whether it is a part of folder name or it is a next argument to the command.
You need to escape the blank space. There are multiple ways to to it. For example wrap the path with double quotes:
"D:\Some Folder\SomeMore Folder\AgainFolder\myPythonFolder\Gotit.exe"
For more ways see this post
os.system("\"%s\"" % GotitexePath)
A the previous replies say, you need to add additional quotation marks around the path for the windows command line.

Python for Data Analysis, Chapter 2, first example

I'm following along with the examples in a translated version of Wes McKinney's "Python for Data Analysis" and I was blocked in first example of Chapter 2
I think my problem arose because I saved a data file in a wrong path. is that right?
I stored a file, usagov_bitly_data2012-03-16-1331923249.txt, in C:\Users\HRR
and also stored folder, pydata-book-mater, that can be downloaded from http://github.com/pydata-book in C:\Users\HRR\Anaconda2\Library\bin.
Depends.
You might change the location you save your File or eddit the path you give to your code in Line 10. Since you're yousing relativ Paths i guess your script runs in C:\Users\HRR\Anaconda2\Library\bin, which means you have to go back to C:\Users\HRR or use an absolute Path ... or move the File, but hell you don't want to move a file every time you want to open it, like moving word files into msoffice file to open it, so try to change the Path.
And allways try harder ;)
In python open() will open from the current directory down unless given a full path (in linux that starts with / and windows <C>://). In your case the command is open the folder ch02 in the directory the script is running from and then open usagov_bitly_data2012-03-16-1331923249.txt in that folder.
Since you are storing the text file in C:\Users\HRR\usagov_bitly_data2012-03-16-1331923249.txt and you did not specify the directory of the script. I recommend the following command instead open(C:\\Users\\HRR\\usagov_bitly_data2012-03-16-1331923249.txt)
Note: the double \ is to escape the characters and avoid tabs and newlines showing up in the path.

Python raw input directory that has a space is not working?

When I prompt the user for a directory using raw_input, it works as long as I have a folder that doesn't have a space in it. new_folder for example works fine but new folder does not work when I use os.path.isdir.
I know I could just replace the spaces with no space but then that leads to problems down the road as I'm using the absolute path for things later on. So if I change the actual folder name, it's not going to work.
file_directory = raw_input("Drag in a directory:")
if os.path.isdir(file_directory):
print 'This is a directory'
else:
print '\nYou did not enter a directory. Please input a directory, not a file\n'
Why doesn't os.path.isdir see a folder with a space as a directory and how can I fix it?
**edit I forgot to mention this is when I run the script in the command line. When I drag in a folder with no spaces, rawinput equals a string with no quotes. When I drag in a folder with spaces it puts quotes around the input which I think is what's messing it up.
#jasonharper advised me that "The ability to drag a file/folder into a console window exists primarily to support the command line, which requires quotes (or other form of escaping) for pathnames including spaces".
so raw_input().strip('"') solved the problem.

How do I modify program files in Python?

In the actual window where I right code is there a way to insert part of the code into everyline that I already have. Like insert a comma into all lines at the first spot>?
You need a file editor, not python.
Install the appropriate VIM variant for your operating system
Open the file you want to modify using VIM
Type: :%s/^/,/
Type: :wq
If you are in UNIX environment, open up a terminal, cd to the directory your file is in and use the sed command. I think this may work:
sed "s/\n/\n,/" your_filename.py > new_filename.py
What this says is to replace all \n (newline character) to \n, (newline character + comma character) in your_filename.py and to output the result into new_filename.py.
UPDATE: This is much better:
sed "s/^/,/" your_filename.py > new_filename.py
This is very similar to the previous example, however we use the regular expression token ^ which matches the beginning of each line (and $ is the symbol for end).
There are chances this doesn't work or that it doesn't even apply to you because you didn't really provide that much information in your question (and I would have just commented on it, but I can't because I don't have enough reputation or something). Good luck.
Are you talking about the interactive shell? (a.k.a. opening up a prompt and typing python)? You can't go back and edit what those previous commands did (as they have been executed), but you can hit the up arrow to flip through those commands to edit and reexecute them.
If you're doing anything very long, the best bet is to write your program into your text editor of choice, save that file, then launch it.
Adding a comma to the start of every line with Python:
import sys
src = open(sys.argv[1])
dest = open('withcommas-' + sys.argv[1],'w')
for line in src:
dest.write(',' + line)
src.close()
dest.close()
Call like so: C:\Scripts>python commaz.py cc.py. This is a bizzare thing to do, but who am I to argue.
Code is data. You could do this like you would with any other text file. Open the file, read the line, stick a comma on the front of it, then write it back to file.
Also, most modern IDEs/text editors have the ability to define macros. You could post a question asking for specific help for your editor. For example, in Emacs I would use C-x ( to start defining a macro, then ',' to write a comma, then C-b C-n to go back a character and down a line, then C-x ) to end my macro. I could then run this macro with C-x e, pressing e to execute it an additional time.

running a system command in a python script

I have been going through "A byte of Python" to learn the syntax and methods etc...
I have just started with a simple backup script (straight from the book):
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
Right, it fails. If I run the zip command in the terminal it works fine. I think it fails because the zip_command is never actually run. And I don't know how to run it.
Simply typing out zip_command does not work. (I am using python 3.1)
Are you sure that the Python script is seeing the same environment you have access to when you enter the command manually in the shell? It could be that zip isn't on the path when Python launches the command.
It would help us if you could format your code as code; select the code parts, and click on the "Code Sample" button in the editor toolbar. The icon looks like "101/010" and if you hold the mouse pointer over it, the yellow "tool tip" box says "Code Sample <pre></pre> Ctrl+K"
I just tried it, and if you paste code in to the StackOverflow editor, lines with '#' will be bold. So the bold lines are comments. So far so good.
Your strings seem to contain backslash characters. You will need to double each backslash, like so:
target_dir = 'E:\\Backup'
This is because Python treats the backslash specially. It introduces a "backslash escape", which lets you put a quote inside a quoted string:
single_quote = '\''
You could also use a Python "raw string", which has much simpler rules for a backslash. A raw string is introduced by r" or r' and terminated by " or ' respectively. examples:
# both of these are legal
target_dir = r"E:\Backup"
target_dir = r'E:\Backup'
The next step I recommend is to modify your script to print the command string, and just look at the string and see if it seems correct.
Another thing you can try is to make a batch file that prints out the environment variables, and have Python run that, and see what the environment looks like. Especially PATH.
Here is a suggested example:
set
echo Trying to run zip...
zip
Put those in a batch file called C:\mytest.cmd, and then have your Python code run it:
result_code = os.system("C:\\mytest.cmd")
print('Result of running mytest was code', result_code)
If it works, you will see the environment variables printed out, then it will echo "Trying to run zip...", then if zip runs it will print a message with the version number of zip and how to run it.
zip command only work in linux not for windows.. thats why it make an error..

Categories