CMD in Windows 7 does not execute command (Python Django) - python

Ok people at this link for pysec as the technical solution is explained we have some code that you must type to the command prompt (i think because it has a dollar sign in front):
$ cd ~/path/to/pysec && python -c "import sqlite3; sqlite3.connect('edgar.db')"
$ mv ./local-settings-example.py ./local-settings.py
$ mkdir ./pysec/data
However whenever i go to C:\Python27\pysec-master which is the location where the pysec file is stored (according to instructions) and type these commands exactly as i see them i get that the system cannot find the path specified.
Like this
C:\Python27\pysec-master>cd ~/path/to/pysec && python -c
cmd response --> The system cannot find the path specified.
C:\Python27\pysec-master>cd ~/path/to/pysec && python -c "import sqlite3; sqlite3.connect('edgar.db')"
cmd response --> The system cannot find the path specified.
C:\Python27\pysec-master>mv ./local-settings-example.py ./local-settings.py
cmd response --> 'mv' is not recognized as an internal or external command, operable program or batch file.
C:\Python27\pysec-master>mkdir ./pysec/data
cmd response --> The syntax of the command is incorrect.
What seems to be the problem? Don't you have to type these commands in the cmd since they have a dollar sign?

ANSWER FOR THIS QUESTION IS PROVIDED FROM THE COMMENTS UNDER THE QUESTION BY USER Stephan
I decided to put the all together in on place>
cd ~..., mv .` and mkdir .\ looks more like unix syntax than windows-cmd. cd and mkdir work on both platforms, but with different syntax. The cmd-version of mv is move.(ANSWER)
also /path/to/pysec tells you, that you should put in the path to pysec, not the string "\path\to\pysec"(ANSWER)
Can we transform these commands to Windows syntax?(QUESTION)
Should we put the path to pysec like this: C:\Python27\pysec-master i mean the full or absolute as it is called path? Because it that tutorial I can see that the example is trimmed as cd ~/path/to/pysec`(QUESTION)
the tilde (~) has a special meaning in unix. I don't speak unix, but I think it means "Systemdrive". The CMD command would be: cd /d "c:\Python27\pysec-master" (in CMD use \, in unix it's /). Instead of mv use move (ANSWER)
Only the third command does not seem to work mkdir ./pysec/data well I think there muse be something different for windows (QUESTION)
mkdir .\pysec\data ... You remember? "in CMD use \, in unix it's /"(ANSWER)
THANK YOU FOR THE SUPPORT

Related

b"'rm' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" , how to resolve this? [duplicate]

I need a way to recursively delete a folder and its children.
Is there a prebuilt tool for this, or do I need to write one?
DEL /S doesn't delete directories.
DELTREE was removed from Windows 2000+
RMDIR or RD if you are using the classic Command Prompt (cmd.exe):
rd /s /q "path"
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
If you are using PowerShell you can use Remove-Item (which is aliased to del, erase, rd, ri, rm and rmdir) and takes a -Recurse argument that can be shorted to -r
rd -r "path"
admin:
takeown /r /f folder
cacls folder /c /G "ADMINNAME":F /T
rmdir /s folder
Works for anything including sys files
EDIT: I actually found the best way which also solves file path too long problem as well:
mkdir \empty
robocopy /mir \empty folder
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
Go to the path and trigger this command.
rd /s /q "FOLDER_NAME"
/s : Removes the specified directory and all subdirectories including any files. Use /s to remove a tree.
/q : Runs rmdir in quiet mode. Deletes directories without confirmation.
/? : Displays help at the command prompt.
You can install cygwin, which has rm as well as ls etc.
For deleting a directory (whether or not it exists) use the following:
if exist myfolder ( rmdir /s/q myfolder )
rm -r -fo <path>
is the closest you can get in Windows PowerShell. It is the abbreviation of
Remove-Item -Recurse -Force -Path <path>
(more details).
The accepted answer is great, but assuming you have Node installed, you can do this much more precisely with the node library "rimraf", which allows globbing patterns. If you use this a lot (I do), just install it globally.
yarn global add rimraf
then, for instance, a pattern I use constantly:
rimraf .\**\node_modules
or for a one-liner that let's you dodge the global install, but which takes slightly longer for the the package dynamic download:
npx rimraf .\**\node_modules
via Powershell
Remove-Item -Recurse -Force "TestDirectory"
via Command Prompt
https://stackoverflow.com/a/35731786/439130
Try this command:
del /s foldername
rmdir /S /Q %DIRNAME%
rmdir /s dirname
First, let’s review what rm -rf does:
C:\Users\ohnob\things>touch stuff.txt
C:\Users\ohnob\things>rm -rf stuff.txt
C:\Users\ohnob\things>mkdir stuff.txt
C:\Users\ohnob\things>rm -rf stuff.txt
C:\Users\ohnob\things>ls -l
total 0
C:\Users\ohnob\things>rm -rf stuff.txt
There are three scenarios where rm -rf is commonly used where it is expected to return 0:
The specified path does not exist.
The specified path exists and is a directory.
The specified path exists and is a file.
I’m going to ignore the whole permissions thing, but nobody uses permissions or tries to deny themselves write access on things in Windows anyways (OK, that’s meant to be a joke…).
First set ERRORLEVEL to 0 and then delete the path only if it exists, using different commands depending on whether or not it is a directory. IF EXIST does not set ERRORLEVEL to 0 if the path does not exist, so setting the ERRORLEVEL to 0 first is necessary to properly detect success in a way that mimics normal rm -rf usage. Guarding the RD with IF EXIST is necessary because RD, unlike rm -f, will throw an error if the target does not exist.
The following script snippet assumes that DELPATH is prequoted. (This is safe when you do something like SET DELPATH=%1. Try putting ECHO %1 in a .cmd and passing it an argument with spaces in it and see what happens for yourself). After the snippet completes, you can check for failure with IF ERRORLEVEL 1.
: # Determine whether we need to invoke DEL or RD or do nothing.
SET DELPATH_DELMETHOD=RD
PUSHD %DELPATH% 2>NUL
IF ERRORLEVEL 1 (SET DELPATH_DELMETHOD=DEL) ELSE (POPD)
IF NOT EXIST %DELPATH% SET DELPATH_DELMETHOD=NOOP
: # Reset ERRORLEVEL so that the last command which
: # otherwise set it does not cause us to falsely detect
: # failure.
CMD /C EXIT 0
IF %DELPATH_DELMETHOD%==DEL DEL /Q %DELPATH%
IF %DELPATH_DELMETHOD%==RD RD /S /Q %DELPATH%
Point is, everything is simpler when the environment just conforms to POSIX. Or if you install a minimal MSYS and just use that.
Here is what you need to do...
Create a batch file with the following line
RMDIR /S %1
Save your batch file as Remove.bat and put it in C:\windows
Create the following registry key
HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)
Launch regedit and update the default value HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)\default
with the following value
"c:\windows\REMOVE.bat" "%1"
Thats it! Now you can right click any directory and use the RMDIR function
LATE BUT IMPORTANT ANSWER to anyone who is having troubles installing npm packages on windows machine and if you are seeing error saying "rm -rf..." command not found.
You can use the bash cli to run rm command on windows.
for npm users, you can change the npm's config to npm config set script-shell "C:\Program Files\Git\bin\bash.exe" this way if the npm package you are trying to install has a post install script that uses rm -rf command, you will be able to run that rm command without needing to change anything in the npm package or disabling the post install scripts config. (For example, styled-components uses rm command in their post install scripts)
If you want to just use the rm command, you can easily use the bash and pass the arguments.
So yes, you can use the 'rm' command on windows.
As a sidenode:
From the linux version with all subdirs (recursive) + force delete
$ rm -rf ./path
to PowerShell
PS> rm -r -fo ./path
which has the close to same params (just seperated) (-fo is needed, since -f could match different other params)
note:
Remove-Item ALIASE
ri
rm
rmdir
del
erase
rd
in powershell, rm is alias of Remove-Item, so remove a file,
rm -R -Fo the_file
is equivalent to
Remove-Item -R -Fo the_file
if you feel comfortable with gnu rm util, you can the rm util by choco package manager on windows.
install gnu utils in powershell using choco:
choco install GnuWin
finally,
rm.exe -rf the_file
You can install GnuWin32 and use *nix commands natively on windows. I install this before I install anything else on a minty fresh copy of windows. :)
Using Powershell 5.1
get-childitem *logs* -path .\ -directory -recurse | remove-item -confirm:$false -recurse -force
Replace logs with the directory name you want to delete.
get-childitem searches for the children directory with the name recursively from current path (.).
remove-item deletes the result.
USE AT YOUR OWN RISK. INFORMATION PROVIDED 'AS IS'. NOT TESTED EXTENSIVELY.
Right-click Windows icon (usually bottom left) > click "Windows PowerShell (Admin)" > use this command (with due care, you can easily delete all your files if you're not careful):
rd -r -include *.* -force somedir
Where somedir is the non-empty directory you want to remove.
Note that with external attached disks, or disks with issues, Windows sometimes behaves odd - it does not error in the delete (or any copy attempt), yet the directory is not deleted (or not copied) as instructed. (I found that in this case, at least for me, the command given by #n_y in his answer will produce errors like 'get-childitem : The file or directory is corrupted and unreadable.' as a result in PowerShell)
In powershell rm -recurse -force works quite well.
here is what worked for me:
Just try decreasing the length of the path.
i.e :: Rename all folders that lead to such a file to smallest possible names. Say one letter names. Go on renaming upwards in the folder hierarchy.
By this u effectively reduce the path length.
Now finally try deleting the file straight away.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Folder\shell\rmdir\command]
#="cmd.exe /s /c rmdir "%V""
There is also deltree if you're on an older version of windows.
You can learn more about it from here:
SS64: DELTREE - Delete all subfolders and files.

Python Readline on macOS behaves differently than on Linux/Windows

A project I'm working on uses a custom CLI handler instead of Python's cmd.Cmd class. Without getting too much in detail, the handler features TAB-key completion to assist the operator with command usage. The feature works as expected on Windows (using pyreadline) and Linux (using GNU's readline).
Here is an example of the expected behavior (assume "cmd > " is the prompt and that [TAB] is a push of the TAB key):
cmd > [TAB]
cd exit load save # all the available commands
cmd > c[TAB] # autocompletes to 'cd'
cmd > cd [TAB]
cd ./folder1 cd ./folder2 cd ./folder3 # folders in the cwd
cmd > cd C:\[TAB]
cd C:\Users cd C:\Windows... # enumerates folders in C:\ (on windows)
cmd > cd /[TAB]
cd /bin cd /opt cd /usr... # enumerates folders from root (on linux)
The custom class defines the following tab completion method, which is set using readline.set_completer():
def tab_completer(self, text, state):
# rl delims set to "" so we get the whole line as a single string
words = re.split(r'[\s\t\n]+', text)
# find_subcompleter populates a list of possible matches or next words
# each command implements its own completer_stub depending on the function (ex: cd will complete directory names)
retval = self.find_subcompleter(words.pop())
try:
return retval[state]
except IndexError:
return None
The function works as expected on Windows (10, Python 3.6.6) and Linux (CentOS 7, Python 3.6.8), but something strange happens on macOS (10.15.7, Python 3.8.2 via xcode on zsh terminal):
cmd > [TAB]
cd exit load save # this is good
cmd > c[TAB] # still autocompletes to 'cd', good
cmd > cd [TAB]
cd exit load save # as if I've typed nothing!
For those of you wondering, this behavior happens with ANY command, not just with cd.
I'm aware that the underlying readline implementation on macOS uses libedit due to GNU licensing. I just haven't seen anyone else (to date) mention this difference on any other forums. A possible solution that comes to mind is to add a conditional for libedit implementations to use get_line_buffer() and redisplay() to mimic the correct behavior. Any pointers in the right direction are appreciated!
Thank you

Create terminal name for execute python script in Ubuntu

I have a python file in: '/home/username/scripts/pyscript' and I want set a word for execute directly this script.
I want do this "python3 /home/username/scripts/pyscript/main.py arg1 arg2" but looks like
this "myscript arg1 arg2"
Is this posible?
Thank you anyway.
It is possibile in a number of ways. Links are for Bash, supposedly your shell but the ideas always apply.
First option: make a shell alias
alias myscript='python3 /home/username/scripts/pyscript/main.py'
Be sure to add the alias to your .profile to make it survive logout.
Second option: define a wrapper script. Create a file with the following content, named after your desired command (e.g. myscript):
#!/bin/bash
python3 /home/username/scripts/pyscript/main.py "$#"
save it and make it executable, then call it :
chmod +x myscript
./myscript arg1 arg2
Be sure to copy the script in a folder in your PATH (check where with echo $PATH) to be able to call it from any folder.
You can also use pyinstaller to create a single file executable:
Step 1: Install pyinstaller
[Note: best practice is to do this in a virutalenv]
$ pip install pyinstaller
Step 2: Run pyinstaller against your script
$ pyinstaller --console --onefile /home/username/scripts/pyscript
$ pyinstaller pyscript.spec # use this after the first run
Step 3: Test the generated executable
$ cd /home/username/scripts/dist # generated by pyinstaller
$ pyscript arg1 arg2
Step 4: Leverage the $PATH variable
$ cp /home/username/scripts/dist/pyscript /usr/bin
You should now be able to run the executable from anywhere.
It should be noted that the executable that is generated is OS specific. For example, if you generate it on an Ubuntu machine, it will only run on Ubuntu (Debian based). The same holds true for Windows and other Linux distros.
Finally I solver with the help of #pierpaciugo
I add a alias at the end of the .bashrc for make it persistent:
alias create='bash /home/username/Programming/Python/GithubAPI/script.sh'
I couldn't use only alias because I have my python dependencies on a virtual environment so if I try this i could not add params to my python script.
For that I create this bash script:
#!/bin/bash
source /home/username/Programming/Python/GithubAPI/venv/bin/activate && python3 /home/username/Programming/Python/GithubAPI/main.py $# && deactivate
Now I can write "create param1 param2" and it works.
I am using all global paths but could be a good idea add the script in a folder in my PATH.

Error in check_call() subprocess, executing 'mv' unix command: "Syntax error: '(' unexpected"

I'm making a python script for Travis CI.
.travis.yml
...
script:
- support/travis-build.py
...
The python file travis-build.py is something like this:
#!/usr/bin/env python
from subprocess import check_call
...
check_call(r"mv !(my_project|cmake-3.0.2-Darwin64-universal) ./my_project/final_folder", shell=True)
...
When Travis building achieves that line, I'm getting an error:
/bin/sh: 1: Syntax error: "(" unexpected
I just tried a lot of different forms to write it, but I get the same result. Any idea?
Thanks in advance!
Edit
My current directory layout:
- my_project/final_folder/
- cmake-3.0.2-Darwin64-universal/
- fileA
- fileB
- fileC
I'm trying with this command to move all the current files fileA, fileB and fileC, excluding my_project and cmake-3.0.2-Darwin64-universal folders into ./my_project/final_folder. If I execute this command on Linux shell, I get my aim but not through check_call() command.
Note: I can't move the files one by one, because there are many others
I don't know which shell Travis are using by default because I don't specify it, I only know that if I write the command in my .travis.yml:
.travis.yml
...
script:
# Here is the previous Travis code
- mv !(my_project|cmake-3.0.2-Darwin64-universal) ./my_project/final_folder
...
It works. But If I use the script, it fails.
I found this command from the following issue:
How to use 'mv' command to move files except those in a specific directory?
You're using the bash feature extglob, to try to exclude the files that you're specifying. You'll need to enable it in order to have it exclude the two entries you're specifying.
The python subprocess module explicitly uses /bin/sh when you use shell=True, which doesn't enable the use of bash features like this by default (it's a compliance thing to make it more like original sh).
If you want to get bash to interpret the command; you have to pass it to bash explicitly, for example using:
subprocess.check_call(["bash", "-O", "extglob", "-c", "mv !(my_project|cmake-3.0.2-Darwin64-universal) ./my_project/final_folder"])
I would not choose to do the job in this manner, though.
Let me try again: in which shell do you expect your syntax !(...) to work? Is it bash? Is it ksh? I have never used it, and a quick search for a corresponding bash feature led nowhere. I suspect your syntax is just wrong, which is what the error message is telling you. In that case, your problem is entirely independent form python and the subprocess module.
If a special shell you have on your system supports this syntax, you need to make sure that Python is using the same shell when invoking your command. It tells you which shell it has been using: /bin/sh. This is usually just a link to the real shell executable. Does it point to the same shell you have tested your command in?
Edit: the SO solution you referenced contains the solution in the comments:
Tip: Note however that using this pattern relies on extglob. You can
enable it using shopt -s extglob (If you want extended globs to be
turned on by default you can add shopt -s extglob to .bashrc)
Just to demonstrate that different shells might deal with your syntax in different ways, first using bash:
$ !(uname)
-bash: !: event not found
And then, using /bin/dash:
$ !(uname)
Linux
The argument to a subprocess.something method must be a list of command line arguments. Use e.g. shlex.split() to make the string be split into correct command line arguments:
import shlex, subprocess
subprocess.check_call( shlex.split("mv !(...)") )
EDIT:
So, the goal is to move files/directories, with the exemption of some file(s)/directory(ies). By playing around with bash, I could get it to work like this:
mv `ls | grep -v -e '\(exclusion1\|exclusion2\)'` my_project
So in your situation that would be:
mv `ls | grep -v -e '\(myproject\|cmake-3.0.2-Darwin64-universal\)'` my_project
This could go into the subprocess.check_call(..., shell=True) and it should do what you expect it to do.

pwd vs directory of file

I have a file and I want to get the directory that file is in. In python, I would do:
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
How would I do the same thing in a shell script? If I use pwd I would get the current directory of the folder I am executing the command from and not the folder of the file I am executing (which is what I need).
When you're executing a shell script, $0 is the name of the script you're executing (see Special Parameters in the Variables chapter of the Bash Guide for Beginners), equivalent to sys.argv[0] in Python (unless you've called shift).
The dirname command does the same thing as os.path.dirname in Python.
There's no portable direct equivalent to os.path.abspath or os.path.realpath, and $0. There are platform-specific ways to do this (e.g., readlink -f on systems with a GNU userland), or you manually combine the pwd with the path. See this question at Unix for a variety of different ways to do that, but mrfripp's answer seems like the most portable:
abspath=$(unset CDPATH && cd "$(dirname "$0")" && echo ${PWD}/$(basename "$0"))
Or, of course, you can just ask Python to do it:
abspath=$(python -c "import os; print(os.path.realpath(\"$0\"))"
absdir=$(dirname "${abspath}")
One solution is:
FILE_PATH=`realpath $0`
FILE_DIR=`dirname $FILE_PATH`
Or in bash-like shells:
FILE_DIR=$(dirname $(realpath $0))
Note that realpath is only guaranteed to be available on GNU-based systems (e.g. Linux).

Categories