string ftp_mkdir ($ftp_connection, $directory_name)Parameter: This function takes two parameters as above and described below:
- $ftp_connection:This is a required parameter and is used to specify the ftp connection in which the directory is created.
- $directory_name:this is a required parameter used to specify the name of the directory to be created.
- This function is available for PHP 4.0.0 and above.
- Following example cannot be launched in the online IDE. So try running on some PHP hosting server or localhost with the correct ftp server name and correct username and password.
// Connect to ftp server
// Use the ftp server address
$fserver
=
"ftp.gfg.org"
;
// Use ftp username
$fuser
=
"username"
;
// Use ftp password
$fpass
=
"password"
;
// Connect to ftp server
$f_conn
= ftp_connect (
$fserver
)
or
die
(
"Could not connect to $fserver"
);
// Authentication on the ftp server
$login
= ftp_login (
$f_conn
,
$fuser
,
$fpass
);
// Name of the directory to be created
$dir
=
"testdirectory"
;
// Create directory
if
(ftp_mkdir (
$f_conn
,
$dir
)) {
// Execute if directory created successfully
echo
"$dir Successfully created"
;
}
else
{
// Execute if directory creation fails
echo
"Error while creating $dir"
;
}
// Close ftp connection
ftp_close (
$f_conn
);
?>
Output:testdirectory Successfully created
Example 2:If a child directory is created, everything will be the same as before, except for $dir, i.e. directory name.
// Connect to ftp server
// Use the ftp server address
$fserver
=
"ftp.exampleserver.com"
;
// Use ftp username
$fuser
=
"username"
;
// Use ftp password
$fpass
=
"password"
;
// Connect to ftp server
$f_conn
= ftp_connect (
$fserver
)
or
die
(
"Could not connect to $fserver"
);
// Authentication on the ftp server
$login
= ftp_login (
$f_conn
,
$fuser
,
$fpass
);
// Name of the directory to be created
$dir
=
"testdirectory / childdirectory"
;
// Create directory
if
(ftp_mkdir (
$f_conn
,
$dir
)) {
// Execute if directory created successfully
echo
"$dir Successfully created"
;
}
else
{
// Execute if directory creation fails
echo
"Error while creating $dir"
;
}
// Close ftp connection
ftp_close (
$f_conn
);
?>
Output:testdirectory / childdirectory Successfully created
Note.If the directory name already exists, an error is thrown.Link: http://php.net/manual/en/function.ftp-mkdir.php
PHP ftp_mkdir () function: StackOverflow Questions
Python"s equivalent of && (logical-and) in an if-statement
Question by delete
Here"s my code:
def front_back(a, b):
# +++your code here+++
if len(a) % 2 == 0 && len(b) % 2 == 0:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return
I"m getting an error in the IF conditional.
What am I doing wrong?
Answer #1:
You would want and
instead of &&
.
Answer #2:
Python uses and
and or
conditionals.
i.e.
if foo == "abc" and bar == "bac" or zoo == "123":
# do something
Answer #3:
I"m getting an error in the IF conditional. What am I doing wrong?
There reason that you get a SyntaxError
is that there is no &&
operator in Python. Likewise ||
and !
are not valid Python operators.
Some of the operators you may know from other languages have a different name in Python.
The logical operators &&
and ||
are actually called and
and or
.
Likewise the logical negation operator !
is called not
.
So you could just write:
if len(a) % 2 == 0 and len(b) % 2 == 0:
or even:
if not (len(a) % 2 or len(b) % 2):
Some additional information (that might come in handy):
I summarized the operator "equivalents" in this table:
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
See also Python documentation: 6.11. Boolean operations.
Besides the logical operators Python also has bitwise/binary operators:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
There is no bitwise negation in Python (just the bitwise inverse operator ~
- but that is not equivalent to not
).
See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.
The logical operators (like in many other languages) have the advantage that these are short-circuited.
That means if the first operand already defines the result, then the second operator isn"t evaluated at all.
To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually
evaluated because of the print statements:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
As you can see only one print statement is executed, so Python really didn"t even look at the right operand.
This is not the case for the binary operators. Those always evaluate both operands:
>>> res = print_and_return(False) & print_and_return(True);
False
True
But if the first operand isn"t enough then, of course, the second operator is evaluated:
>>> res = print_and_return(True) and print_and_return(False);
True
False
To summarize this here is another Table:
+-----------------+-------------------------+
| Expression | Right side evaluated? |
+=================+=========================+
| `True` and ... | Yes |
+-----------------+-------------------------+
| `False` and ... | No |
+-----------------+-------------------------+
| `True` or ... | No |
+-----------------+-------------------------+
| `False` or ... | Yes |
+-----------------+-------------------------+
The True
and False
represent what bool(left-hand-side)
returns, they don"t have to be True
or False
, they just need to return True
or False
when bool
is called on them (1).
So in Pseudo-Code(!) the and
and or
functions work like these:
def and(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return evaluate(expr2)
else:
return left
def or(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return left
else:
return evaluate(expr2)
Note that this is pseudo-code not Python code. In Python you cannot create functions called and
or or
because these are keywords.
Also you should never use "evaluate" or if bool(...)
.
Customizing the behavior of your own classes
This implicit bool
call can be used to customize how your classes behave with and
, or
and not
.
To show how this can be customized I use this class which again print
s something to track what is happening:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
print("__bool__ called on {!r}".format(self))
return bool(self.value)
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
So let"s see what happens with that class in combination with these operators:
>>> if Test(True) and Test(False):
... pass
__bool__ called on Test(True)
__bool__ called on Test(False)
>>> if Test(False) or Test(False):
... pass
__bool__ called on Test(False)
__bool__ called on Test(False)
>>> if not Test(True):
... pass
__bool__ called on Test(True)
If you don"t have a __bool__
method then Python also checks if the object has a __len__
method and if it returns a value greater than zero.
That might be useful to know in case you create a sequence container.
See also 4.1. Truth Value Testing.
NumPy arrays and subclasses
Probably a bit beyond the scope of the original question but in case you"re dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool
call
will raise the dreaded ValueError
:
>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
In these cases you can use the logical and function from NumPy which performs an element-wise and
(or or
):
>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False, True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False, True, True])
If you"re dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:
>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False, True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False, True, True])
(1)
That the bool
call on the operands has to return True
or False
isn"t completely correct. It"s just the first operand that needs to return a boolean in it"s __bool__
method:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)
That"s because and
actually returns the first operand if the first operand evaluates to False
and if it evaluates to True
then it returns the second operand:
>>> x1
Test(10)
>>> x2
Test(False)
Similarly for or
but just the other way around:
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
However if you use them in an if
statement the if
will also implicitly call bool
on the result. So these finer points may not be relevant for you.
How do you get the logical xor of two variables in Python?
Question by Zach Hirsch
How do you get the logical xor of two variables in Python?
For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
The ^
operator seems to be bitwise, and not defined on all objects:
>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: "str" and "str"
Answer #1:
If you"re already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
Answer #2:
You can always use the definition of xor to compute it from other logical operations:
(a and not b) or (not a and b)
But this is a little too verbose for me, and isn"t particularly clear at first glance. Another way to do it is:
bool(a) ^ bool(b)
The xor operator on two booleans is logical xor (unlike on ints, where it"s bitwise). Which makes sense, since bool
is just a subclass of int
, but is implemented to only have the values 0
and 1
. And logical xor is equivalent to bitwise xor when the domain is restricted to 0
and 1
.
So the logical_xor
function would be implemented like:
def logical_xor(str1, str2):
return bool(str1) ^ bool(str2)
Credit to Nick Coghlan on the Python-3000 mailing list.
PHP ftp_mkdir () function: StackOverflow Questions
mkdir -p functionality in Python
Is there a way to get functionality similar to mkdir -p
on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
Answer #1:
For Python ‚â• 3.5, use pathlib.Path.mkdir
:
import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)
The exist_ok
parameter was added in Python 3.5.
For Python ‚â• 3.2, os.makedirs
has an optional third argument exist_ok
that, when True
, enables the mkdir -p
functionality—unless mode
is provided and the existing directory has different permissions than the intended ones; in that case, OSError
is raised as previously:
import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)
For even older versions of Python, you can use os.makedirs
and ignore the error:
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python ‚â• 2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
# possibly handle other errno cases here, otherwise finally:
else:
raise
Answer #2:
In Python >=3.2, that"s
os.makedirs(path, exist_ok=True)
In earlier versions, use @tzot"s answer.
Answer #3:
This is easier than trapping the exception:
import os
if not os.path.exists(...):
os.makedirs(...)
Disclaimer This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you"re writing something more sophisticated than a simple throwaway script running in a controlled environment, you"re better off going with the accepted answer that requires only one system call.
UPDATE 2012-07-27
I"m tempted to delete this answer, but I think there"s value in the comment thread below. As such, I"m converting it to a wiki.
PHP ftp_mkdir () function: StackOverflow Questions
Why is reading lines from stdin much slower in C++ than Python?
I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I"m not yet an expert Pythonista, please tell me if I"m doing something wrong or if I"m misunderstanding something.
(TLDR answer: include the statement: cin.sync_with_stdio(false)
or just use fgets
instead.
TLDR results: scroll all the way down to the bottom of my question and look at the table.)
C++ code:
#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps << endl;
} else
cerr << endl;
return 0;
}
// Compiled with:
// g++ -O3 -o readline_test_cpp foo.cpp
Python Equivalent:
#!/usr/bin/env python
import time
import sys
count = 0
start = time.time()
for line in sys.stdin:
count += 1
delta_sec = int(time.time() - start_time)
if delta_sec >= 0:
lines_per_sec = int(round(count/delta_sec))
print("Read {0} lines in {1} seconds. LPS: {2}".format(count, delta_sec,
lines_per_sec))
Here are my results:
$ cat test_lines | ./readline_test_cpp
Read 5570000 lines in 9 seconds. LPS: 618889
$ cat test_lines | ./readline_test.py
Read 5570000 lines in 1 seconds. LPS: 5570000
I should note that I tried this both under Mac OS X v10.6.8 (Snow Leopard) and Linux 2.6.32 (Red Hat Linux 6.2). The former is a MacBook Pro, and the latter is a very beefy server, not that this is too pertinent.
$ for i in {1..5}; do echo "Test run $i at `date`"; echo -n "CPP:"; cat test_lines | ./readline_test_cpp ; echo -n "Python:"; cat test_lines | ./readline_test.py ; done
Test run 1 at Mon Feb 20 21:29:28 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 2 at Mon Feb 20 21:29:39 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 3 at Mon Feb 20 21:29:50 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 4 at Mon Feb 20 21:30:01 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 5 at Mon Feb 20 21:30:11 EST 2012
CPP: Read 5570001 lines in 10 seconds. LPS: 557000
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Tiny benchmark addendum and recap
For completeness, I thought I"d update the read speed for the same file on the same box with the original (synced) C++ code. Again, this is for a 100M line file on a fast disk. Here"s the comparison, with several solutions/approaches:
Implementation
Lines per second
python (default)
3,571,428
cin (default/naive)
819,672
cin (no sync)
12,500,000
fgets
14,285,714
wc (not fair comparison)
54,644,808
Answer #1:
tl;dr: Because of different default settings in C++ requiring more system calls.
By default, cin
is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:
std::ios_base::sync_with_stdio(false);
Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks. This reduces the number of system calls, which are typically relatively expensive. However, since the FILE*
based stdio
and iostreams
often have separate implementations and therefore separate buffers, this could lead to a problem if both were used together. For example:
int myvalue1;
cin >> myvalue1;
int myvalue2;
scanf("%d",&myvalue2);
If more input was read by cin
than it actually needed, then the second integer value wouldn"t be available for the scanf
function, which has its own independent buffer. This would lead to unexpected results.
To avoid this, by default, streams are synchronized with stdio
. One common way to achieve this is to have cin
read each character one at a time as needed using stdio
functions. Unfortunately, this introduces a lot of overhead. For small amounts of input, this isn"t a big problem, but when you are reading millions of lines, the performance penalty is significant.
Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the sync_with_stdio
method.
Answer #2:
Just out of curiosity I"ve taken a look at what happens under the hood, and I"ve used dtruss/strace on each test.
C++
./a.out < in
Saw 6512403 lines in 8 seconds. Crunch speed: 814050
syscalls sudo dtruss -c ./a.out < in
CALL COUNT
__mac_syscall 1
<snip>
open 6
pread 8
mprotect 17
mmap 22
stat64 30
read_nocancel 25958
Python
./a.py < in
Read 6512402 lines in 1 seconds. LPS: 6512402
syscalls sudo dtruss -c ./a.py < in
CALL COUNT
__mac_syscall 1
<snip>
open 5
pread 8
mprotect 17
mmap 21
stat64 29
Answer #3:
I"m a few years behind here, but:
In "Edit 4/5/6" of the original post, you are using the construction:
$ /usr/bin/time cat big_file | program_to_benchmark
This is wrong in a couple of different ways:
You"re actually timing the execution of cat
, not your benchmark. The "user" and "sys" CPU usage displayed by time
are those of cat
, not your benchmarked program. Even worse, the "real" time is also not necessarily accurate. Depending on the implementation of cat
and of pipelines in your local OS, it is possible that cat
writes a final giant buffer and exits long before the reader process finishes its work.
Use of cat
is unnecessary and in fact counterproductive; you"re adding moving parts. If you were on a sufficiently old system (i.e. with a single CPU and -- in certain generations of computers -- I/O faster than CPU) -- the mere fact that cat
was running could substantially color the results. You are also subject to whatever input and output buffering and other processing cat
may do. (This would likely earn you a "Useless Use Of Cat" award if I were Randal Schwartz.
A better construction would be:
$ /usr/bin/time program_to_benchmark < big_file
In this statement it is the shell which opens big_file, passing it to your program (well, actually to time
which then executes your program as a subprocess) as an already-open file descriptor. 100% of the file reading is strictly the responsibility of the program you"re trying to benchmark. This gets you a real reading of its performance without spurious complications.
I will mention two possible, but actually wrong, "fixes" which could also be considered (but I "number" them differently as these are not things which were wrong in the original post):
A. You could "fix" this by timing only your program:
$ cat big_file | /usr/bin/time program_to_benchmark
B. or by timing the entire pipeline:
$ /usr/bin/time sh -c "cat big_file | program_to_benchmark"
These are wrong for the same reasons as #2: they"re still using cat
unnecessarily. I mention them for a few reasons:
they"re more "natural" for people who aren"t entirely comfortable with the I/O redirection facilities of the POSIX shell
there may be cases where cat
is needed (e.g.: the file to be read requires some sort of privilege to access, and you do not want to grant that privilege to the program to be benchmarked: sudo cat /dev/sda | /usr/bin/time my_compression_test --no-output
)
in practice, on modern machines, the added cat
in the pipeline is probably of no real consequence.
But I say that last thing with some hesitation. If we examine the last result in "Edit 5" --
$ /usr/bin/time cat temp_big_file | wc -l
0.01user 1.34system 0:01.83elapsed 74%CPU ...
-- this claims that cat
consumed 74% of the CPU during the test; and indeed 1.34/1.83 is approximately 74%. Perhaps a run of:
$ /usr/bin/time wc -l < temp_big_file
would have taken only the remaining .49 seconds! Probably not: cat
here had to pay for the read()
system calls (or equivalent) which transferred the file from "disk" (actually buffer cache), as well as the pipe writes to deliver them to wc
. The correct test would still have had to do those read()
calls; only the write-to-pipe and read-from-pipe calls would have been saved, and those should be pretty cheap.
Still, I predict you would be able to measure the difference between cat file | wc -l
and wc -l < file
and find a noticeable (2-digit percentage) difference. Each of the slower tests will have paid a similar penalty in absolute time; which would however amount to a smaller fraction of its larger total time.
In fact I did some quick tests with a 1.5 gigabyte file of garbage, on a Linux 3.13 (Ubuntu 14.04) system, obtaining these results (these are actually "best of 3" results; after priming the cache, of course):
$ time wc -l < /tmp/junk
real 0.280s user 0.156s sys 0.124s (total cpu 0.280s)
$ time cat /tmp/junk | wc -l
real 0.407s user 0.157s sys 0.618s (total cpu 0.775s)
$ time sh -c "cat /tmp/junk | wc -l"
real 0.411s user 0.118s sys 0.660s (total cpu 0.778s)
Notice that the two pipeline results claim to have taken more CPU time (user+sys) than real wall-clock time. This is because I"m using the shell (bash)"s built-in "time" command, which is cognizant of the pipeline; and I"m on a multi-core machine where separate processes in a pipeline can use separate cores, accumulating CPU time faster than realtime. Using /usr/bin/time
I see smaller CPU time than realtime -- showing that it can only time the single pipeline element passed to it on its command line. Also, the shell"s output gives milliseconds while /usr/bin/time
only gives hundredths of a second.
So at the efficiency level of wc -l
, the cat
makes a huge difference: 409 / 283 = 1.453 or 45.3% more realtime, and 775 / 280 = 2.768, or a whopping 177% more CPU used! On my random it-was-there-at-the-time test box.
I should add that there is at least one other significant difference between these styles of testing, and I can"t say whether it is a benefit or fault; you have to decide this yourself:
When you run cat big_file | /usr/bin/time my_program
, your program is receiving input from a pipe, at precisely the pace sent by cat
, and in chunks no larger than written by cat
.
When you run /usr/bin/time my_program < big_file
, your program receives an open file descriptor to the actual file. Your program -- or in many cases the I/O libraries of the language in which it was written -- may take different actions when presented with a file descriptor referencing a regular file. It may use mmap(2)
to map the input file into its address space, instead of using explicit read(2)
system calls. These differences could have a far larger effect on your benchmark results than the small cost of running the cat
binary.
Of course it is an interesting benchmark result if the same program performs significantly differently between the two cases. It shows that, indeed, the program or its I/O libraries are doing something interesting, like using mmap()
. So in practice it might be good to run the benchmarks both ways; perhaps discounting the cat
result by some small factor to "forgive" the cost of running cat
itself.
How do you read from stdin?
I"m trying to do some of the code golf challenges, but they all require the input to be taken from stdin
. How do I get that in Python?
Answer #1:
You could use the fileinput
module:
import fileinput
for line in fileinput.input():
pass
fileinput
will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.
Note: line
will contain a trailing newline; to remove it use line.rstrip()
Answer #2:
There"s a few ways to do it.
sys.stdin
is a file-like object on which you can call functions read
or readlines
if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys
for this to work.)
If you want to prompt the user for input, you can use raw_input
in Python 2.X, and just input
in Python 3.
If you actually just want to read command-line options, you can access them via the sys.argv list.
You will probably find this Wikibook article on I/O in Python to be a useful reference as well.